我有一张这样的桌子
Table1Id | Column2
-------------------
100 | somedata
像这样的人
Table2Id|Table1Id|Name |Value
-------------------------------
500 |100 |name1 |value1
501 |100 |name2 |value2
我要搜索“ name1”和“ value1”,我想用它检索table1中的所有内容。这很容易,但是当我仅从第一行获得数据时,如何检索表2中的其余子项?我想在一个查询中执行此操作,但我想避免子查询,但不确定是否可行。
有人可以修复此查询以返回table2中的另一个子行吗?
SELECT *
FROM Table1 t1
JOIN table2 t2 on t1.Table1Id = t2.Table1Id
WHERE t2.Name = 'name1' AND t2.Value = 'value1'
答案 0 :(得分:1)
不确定在这种情况下为什么要避免子查询,例如,子查询可提供最佳性能。
declare @Table1 table (Table1Id int, Column2 varchar(32));
declare @Table2 table (Table2Id int, Table1Id int, [Name] varchar(32), [Value] varchar(32));
insert into @Table1 (Table1Id, Column2)
select 100, 'somevalue1' union all
select 101, 'somevalue2'
insert into @Table2 (Table2Id, Table1Id, [Name], [Value])
select 500, 100, 'name1', 'value1' union all
select 501, 100, 'name2', 'value2' union all
select 502, 101, 'name3', 'value3' union all
select 503, 101, 'name4', 'value4'
SELECT *
FROM @Table1 T1
INNER JOIN @Table2 T2 on T1.Table1Id = T2.Table1Id
WHERE T1.Table1Id = (
SELECT T2A.Table1Id
FROM @Table2 T2A
WHERE T2A.[Name] = 'name1' AND T2A.[Value] = 'value1'
)
礼物:
Table1Id Column2 Table2Id Table1Id Name Value
100 somevalue1 500 100 name1 value1
100 somevalue1 501 100 name2 value2
答案 1 :(得分:1)
select T1.*, T2.*
FROM Table1 T1
INNER JOIN Table2 T2 on T1.Table1Id = T2.Table1Id
INNER JOIN Table2 Query on T1.id= Query.Table1Id
WHERE Query.[Name] = 'name1' AND Query.[Value] = 'value1'
请注意,如果Table2
和Name
的组合相同的行多于1条Value
,则不会引发错误。
答案 2 :(得分:0)
也许这就是您要寻找的,但不确定:
select *
from Table2 t2
left join Table1 t1 on t1.Table1Id = t2.Table1Id
and t2.Name = 'name1' and t2.Value = 'value1'