简体   繁体   中英

mysql select all rows that have same value from id

I have a sql table like this

id|server_name|other|data|
__|___________|_____|____
1|server1     |data |data
2|server1     |data |data
3|server2     |data |data
4|server3     |data |data

Im trying to find a select statement where I can give it the id and it will return all the rows that have the same server_name as the id I specified.

so I select id=2 and I will get the rows from id 1 and 2.

I tried this but its just returning everything.

SELECT * FROM `backups` WHERE EXISTS(SELECT `server_name` FROM `backups` WHERE `id` = 2);

Any help is appreciated.

SELECT *
FROM backups
WHERE server_name = (SELECT server_name
                     FROM backups
                     WHERE id = 2)

or

SELECT b1.*
FROM backups AS b1
JOIN backups AS b2 ON b1.server_name = b2.server_name
WHERE b2.id = 2

You were close. Just use = to compare each row's server_name with the value returned from your subquery:

SELECT * FROM backups
WHERE server_name = (
  SELECT server_name
  FROM backups
  WHERE id = 2)

You can do it with a join too:

SELECT b2.*
FROM backups b1
JOIN backups b2 ON b2.server_name = b1.server_name
WHERE b1.id = 2

Either way, an index on server_name will help performance.

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