[英]mysql select all rows that have same value from id
I have a sql table like this 我有这样的SQL表
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. 我试图找到一个可以给它提供ID的select语句,它将返回与我指定的ID具有相同server_name的所有行。
so I select id=2 and I will get the rows from id 1 and 2. 所以我选择id = 2,我将从id 1和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: 只需使用=
将每一行的server_name
与子查询返回的值进行比较:
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. 无论哪种方式, server_name
上的索引都将有助于提高性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.