2017-09-21 29 views
-6

我試着查詢,但不具有搜索答案,我有兩個表查詢SQL

table 1

enter image description here

我想設計Linq中的查詢得到有註冊中的所有數據表2在值字段1和值3和值4,在這個例子中我得到表1的數據表1

enter image description here

感謝您使用子查詢協作

+0

爲什麼選票不利? –

回答

0

SELECT * FROM TABLE_1其中id中(從TABLE_2選擇idtable1其中數(1,3,4))由關節

SELECT * FROM T1 TABLE_1加入TABLE_2 T2上t1.id = t2.idtable1其中t2.number在(1,3,4)

0

這將是

select id,idTable1,number 
     from 
     table2 
where idTable1 = 1 

如果我正確理解問題。你的問題有點難以理解。如果應該有一個加入其中

select b.id,a.Idtable1,a.number 
    from table1 b ,table2 a 
    where b.id = a.Idtable1 
0

如果我沒有弄錯你想要什麼,這可能工作。您需要加入表格,然後檢查您想要在哪裏使用的條件。

SELECT a.id, a.value 
FROM TABLE1 a 
INNER JOIN TABLE2 b on a.id=b.idTable1 
WHERE b.number in (1,3,4) 
AND a.id = 1; 
+0

謝謝你的回答,但它是錯誤的,因爲用句子「in」,我得到的數據只符合條件,我想得到有數字1的寄存器和數字3中的其他寄存器和其他寄存器中的數值4,我認爲加上句子「union」就可以工作 –

0

該第一個查詢假定table2.number對於給定的id是唯一的。這可能不是真的。如果是:

select table1.id, table1.value 
from table1 
join table2 
    on table1.id = table2.idTable1 
group by table1.id, table1.value 
having count(*) = 3 
where table2.number in (1,3,4) 

如果「號」可能是一個重複的值(不是每個idTable1唯一的),那麼我們需要確保我們在表2中加入對不同的值:

select table1.id, table1.value 
from table1 
join (select distinct table2.idTable1, table2.number where table2.number in (1,3,4)) t2 
    on table1.id = t2.idTable1 
group by table1.id, table1.value 
having count(*) = 3 
1

這是我怎麼會去了解它 - 我寫的SQL,因爲我在這樣比我在LINQ,而是從一個轉換到另一個應該是直截了當:

select 
    t1.id 
    , t1.value 
from table1 as t1 
    inner join table2 as t21 
     on t21.idTable1 = t1.id 
     and t21.number = 1 
    inner join table2 as t23 
     on t23.idTable1 = t1.id 
     and t23.number = 3 
    inner join table2 as t24 
     on t24.idTable1 = t1.id 
     and t24.number = 4 

此連接到表2的子集三次,一次f或者你想要的每個值。使用「內連接」使邏輯等價於一個AND。