Of course, it is hard to parametrize, but if it important then you can pass the values as table-valued parameter.
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
题
Pardon the title, I've no clue what to call this. So imagine I have this
table_ref
id_x|id_y
---------
6|70
6|71
6|72
6|73
8|70
8|73
9|72
9|73
How can i select id_y
only if it matches id_x= 6 & 8 & 9
?
in this case it should return me 73
the returned result of id_y
will then be used as an inner join in another sql query.
解决方案
Of course, it is hard to parametrize, but if it important then you can pass the values as table-valued parameter.
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
其他提示
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)
Please try this:
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
Yes you can use a plain IN to accomplish that:
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
using inner join :
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
demo here:http://sqlfiddle.com/#!3/28bcb/6
This works even on SQL-Server 2005.
You can use multiple 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
)
That doesn't look nice but it's working and efficient with proper indices.
This should work:
SELECT [id_y]
FROM [table_ref]
WHERE [id_x] IN (6, 8, 9)
GROUP BY [id_y]
HAVING Count(DISTINCT [id_x]) = 3
If you want to get the range of values from a separate table you can do that with:
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)
If you want something a little more general:
SELECT id_y
FROM table_ref
GROUP BY id_y
WHERE COUNT(DISTINCT id_x)) = (SELECT COUNT(DISTINCT id_x)) FROM table_ref)
It return only the value of id_y associated with every id_x in the table, regardless of the number of id_x
How about this?
Select blah
From OtherTable
Where id_y in ( Select id_y from table_ref where id_x in (6,8,9))