我有一个SQL表有条目
+-----------------+------+
| idanother_table | Col1 |
+-----------------+------+
| 11 | 50 |
| 11 | 61 |
| 11 | 62 |
| 12 | 61 |
| 12 | 62 |
| 13 | 50 |
| 13 | 65 |
+-----------------+------+
我想要一个提供此结果的查询
+-----------------+------+
| idanother_table | Col1 |
+-----------------+------+
| 11 | 50 |
| 11 | 61 |
| 11 | 62 |
| 13 | 50 |
| 13 | 65 |
+-----------------+------+
所以获得与id_anothertable and col1 = 50
相关的所有行。
因此,对于id,我们有col1 = 50,我们将获取与该id相关的所有行
也许这个问题是另一个问题的重复,但实际上我不知道如何命名我的问题所以我有任何研究基础
你可以尝试使用IN
SELECT * FROM t
WHERE idanother_table IN
(
SELECT idanother_table
FROM t
where Col1 = 50
)
或者exists
SELECT *
FROM t t1
WHERE exists
(
SELECT 1
FROM t tt
where tt.Col1 = 50 and t1.idanother_table = tt.idanother_table
)
你可以在子查询上使用连接来进行col1 = 50重新调整idanother_table
select * from my_table
inner join (
select idanother_table
from my_table
where col1 = 50
) t on t.idanother_table = my_table.idanother_table
你可以使用exists
SELECT t1.* FROM t t1
WHERE exists
(
SELECT 1
FROM t2
where t1.idanother_table =t2.idanother_table and t2.Col1 = 50
)
我在查询exists
的查询中使用col1 = 50
运算符:
SELECT *
FROM mytable a
WHERE EXISTS (SELECT *
FROM mytable b
WHERE a.idanother_table = b.idanother_table AND
b.col1 = 50)
SELECT idanother_table, Col1
FROM YourTable
WHERE idanother_table IN (SELECT idanother_table
FROM YourTable
WHERE Col1=50
)