2017-09-21 28 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。