mysql根据两列选择行

时间:2014-04-16 07:03:08

标签: mysql sql

例如,表结构如下:

id   test_id
1      aaa
2      b
3      aaa
4      b
5      aaa

问题是我不知道test_id是aaa。我只有id = 3,我想得到行1,3,5的结果,因为它们都有相同的test_id。有人能告诉我如何实现这一目标吗?感谢。

p.s:我不知道如何把这个问题的标题。或者也许有任何重复我找不到?有什么建议?

6 个答案:

答案 0 :(得分:3)

select distinct t1.*
from table_name t1
inner join table_name t2 on t1.test_id=t2.test_id
where t2.id=3

答案 1 :(得分:1)

使用sql子查询:

SELECT * FROM t1 WHERE test_id IN (SELECT test_id FROM t1 WHERE id = '3') 

答案 2 :(得分:1)

使用自联接

获得此功能的另一种方法
SELECT t1.*
FROM `table` t1
JOIN (SELECT test_id FROM `table` WHERE id = 3) t2
USING(test_id)

答案 3 :(得分:0)

子查询的另一种可能性

select id,test_id
from sometable
where test_id = 
(select test_id from sometable where id = 3)

答案 4 :(得分:0)

你可以使用自我加入...... 我不确定mysql .. 这是SQLSERVER代码(可执行文件)..

     select distinct t1.id,t2.test_id 
     from table_id t1
     inner join
     table_id t2
     on
     t1.test_id = t2.test_id

答案 5 :(得分:0)

使用子查询

  

select * from table_name where test_id IN(SELECT test_id FROM table_name WHERE id ='3');

相关问题