简体   繁体   中英

sql: select rows which have the same column value in another column with a single query

example table:

id | value
----------
1  | abc
1  | cb3
1  | dsf
2  | sss
2  | d3

So if the input is "cb3" I want to get all rows with id 1, if the input is "sss" I want to get all rows with id 2. Can this be done with one query instead of two ? (first query is find id and second query bring rows for found id). Also, would a one query approach be faster ?

Thank you in advance.

Try the following, where you replace 'sss' with the value you are searching for:

select * from table t1
where t1.id in (select id from table t2 where value = 'sss')

Note that value seems not to be a key, such that you might get two different groups of ids in your result. That's also the reason why I proposed an t1.id IN (select id ... rather than an t1.id = (select id ... .

you could try this :

SELECT * 
FROM TABLE my_table 
WHERE id IN (SELECT id 
         FROM TABLE my_table 
         WHERE value = input
         )

You can solve it using inner join also.

SELECT S.* 
FROM dataset AS S 
INNER JOIN dataset AS T 
ON S.id = T.id 
WHERE T.value = 'cb3';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM