原谅标题,我不知道该怎么称呼它。 所以想象一下我有这个
table_ref
id_x|id_y
---------
6|70
6|71
6|72
6|73
8|70
8|73
9|72
9|73
如果id_y
与id_x= 6 & 8 & 9
匹配,我该如何选择?{1}}?
在这种情况下,它应该返回73
然后将id_y
的返回结果用作另一个SQL查询中的内部联接。
答案 0 :(得分:37)
当然,很难进行参数化,但如果它很重要,那么你可以将这些值作为表值参数传递。
SELECT T.id_y
FROM table_ref T
JOIN (VALUES (6), (8), (9)) A(id_x)
ON T.id_x = A.id_x
GROUP BY T.id_y
HAVING COUNT(*) = 3
答案 1 :(得分:6)
SELECT distinct [idy]
FROM Table_1
WHERE idy in (SELECT idy FROM Table_1 WHERE idx=6)
AND idy in (SELECT idy FROM Table_1 WHERE idx=8)
AND idy in (SELECT idy FROM Table_1 WHERE idx=9)
答案 2 :(得分:4)
请试试这个:
select a.* from table_ref as a
inner join table_ref as b
on a.id_y = b.id_y
and b.id_x = 8
inner join table_ref as c
on a.id_y = c.id_y
and c.id_x = 9
where a.id_x = 6
答案 3 :(得分:4)
是的,您可以使用普通的IN来实现:
sqlite> SELECT * FROM table_ref;
6|70
6|71
6|72
6|73
8|70
8|73
9|72
9|73
sqlite> SELECT id_y
...> FROM table_ref t
...> WHERE id_x IN (6,8,9)
...> GROUP BY t.id_y
...> HAVING COUNT(*) = 3;
73
答案 4 :(得分:3)
即使在SQL-Server 2005上也是如此。
您可以使用多个EXIST
s:
SELECT DISTINCT t.id_y
FROM dbo.table_ref t
WHERE EXISTS(
SELECT 1 FROM dbo.table_ref t2
WHERE t2.id_y=t.id_y AND t2.id_x = 6
)
AND EXISTS(
SELECT 1 FROM dbo.table_ref t2
WHERE t2.id_y=t.id_y AND t2.id_x = 8
)
AND EXISTS(
SELECT 1 FROM dbo.table_ref t2
WHERE t2.id_y=t.id_y AND t2.id_x = 9
)
这看起来不太好但是它的工作效率和适当的指数都很有效。
答案 5 :(得分:3)
使用内部联接:
SELECT a.id_y
FROM
(SELECT id_x, id_y
FROM table_ref
WHERE id_x =6 )a INNER JOIN
(SELECT id_x, id_y
FROM table_ref
WHERE id_x =8)b on a.id_y = b.id_y
INNER JOIN
(SELECT id_x, id_y
FROM table_ref
WHERE id_x =9)c on b.id_y = c.id_y
答案 6 :(得分:3)
这应该有效:
SELECT [id_y]
FROM [table_ref]
WHERE [id_x] IN (6, 8, 9)
GROUP BY [id_y]
HAVING Count(DISTINCT [id_x]) = 3
如果您想从单独的表中获取值范围,可以使用以下方法获取:
DECLARE @Lookup TABLE (ID INT)
INSERT INTO @Lookup VALUES (6), (8), (9)
SELECT [id_y]
FROM [table_ref]
WHERE [id_x] IN (SELECT [ID] FROM @Lookup)
GROUP BY [id_y]
HAVING Count(DISTINCT [id_x]) = (SELECT Count(DISTINCT [ID]) FROM @Lookup)
答案 7 :(得分:1)
如果你想要一些更通用的东西:
SELECT id_y
FROM table_ref
GROUP BY id_y
WHERE COUNT(DISTINCT id_x)) = (SELECT COUNT(DISTINCT id_x)) FROM table_ref)
它只返回与表中每个id_x关联的id_y的值,而不管id_x的数量
答案 8 :(得分:0)
这个怎么样?
Select blah
From OtherTable
Where id_y in ( Select id_y from table_ref where id_x in (6,8,9))