【发布时间】:2017-09-21 14:59:25
【问题描述】:
【问题讨论】:
-
为什么投反对票?
标签: sql linq sql-server-2012
【问题讨论】:
标签: sql linq sql-server-2012
这就是我的做法 - 我用 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 的子集,一次用于您想要的每个值。使用“内连接”使逻辑等效于 AND。
【讨论】:
通过使用子查询
select * from table_1 where id in (select idtable1 from table_2 where number in (1,3,4))
按关节 select * from table_1 t1 join table_2 t2 on t1.id=t2.idtable1 where t2.number in (1,3,4)
【讨论】:
应该是
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
【讨论】:
如果我没记错你想要什么,这可能会奏效。您需要加入 to 表,然后使用 where 检查您想要的条件。
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;
【讨论】:
第一个查询假设 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 来说不是唯一的),那么我们需要确保我们在 table2 中加入不同的值:
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
【讨论】: