sql在线查询

gv8xihay  于 2021-06-20  发布在  Mysql
关注(0)|答案(5)|浏览(469)

我有一个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相关的所有行
也许这个问题是另一个问题的重复,但我真的不知道如何命名我的问题,所以我有任何研究的基础

ahy6op9u

ahy6op9u1#

你可以用 exists ```
SELECT t1.* FROM t t1
WHERE exists
(
SELECT 1
FROM t2
where t1.idanother_table =t2.idanother_table and t2.Col1 = 50
)

pjngdqdw

pjngdqdw2#

你可以试着用 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
)
ibps3vxo

ibps3vxo3#

SELECT idanother_table, Col1 
FROM YourTable 
WHERE idanother_table IN (SELECT idanother_table 
    FROM YourTable 
    WHERE Col1=50
)
pdkcd3nj

pdkcd3nj4#

我会用 exists 用于检查 col1 = 50 :

SELECT *
FROM   mytable a
WHERE  EXISTS (SELECT *
               FROM   mytable b
               WHERE  a.idanother_table = b.idanother_table AND
                      b.col1 = 50)
vcudknz3

vcudknz35#

您可以对col1=50重新调整另一个表的子查询使用联接

select * from my_table 
inner join (
    select  idanother_table 
    from my_table  
    where col1 = 50  
) t on t.idanother_table = my_table.idanother_table

相关问题