sql查询返回具有相同列值的所有行

时间:2014-04-15 23:20:36

标签: mysql sql

我有一个像

这样的数据库
    column_1 | column_2 | column_3
    ------------------------------
         aaa | bbb      | ccc
         xys | hkj      | fgh
         dfs | jhv      | ccc
         cfg | rty      | fgh
         iyd | olp      | ccc
         gdv | tdr      | www

我想获得结果,以便column_3中具有相同值的所有行与其column_3值一起打印出来

        column_1 | column_3
        --------------------
             aaa | ccc
             dfs | ccc
             iyd | ccc
             cfg | fgh
             xys | fgh
             gdv | www

我知道SELECT DISTINCT column_3 FROM table_name;为我提供了column_3的所有唯一名称,但如何获取依赖于column_1的所有column_3值?

3 个答案:

答案 0 :(得分:1)

你有可能过度思考吗?我相信你想要

 SELECT column_1,
        column_3
   FROM table_name
  ORDER BY column_3, column_1

答案 1 :(得分:0)

Select ...
From table_name As T
Where Exists    (
                Select 1
                From table_name As T2
                Where T2.column_3 = T.column_3
                    And T2.<Primary Key Column> <> T.<Primary Key Column>
                )

显然,您会将<Primary Key Column>替换为唯一标识table_name中每一行的列。如果column_1是该列,那么我们会得到:

Select ...
From table_name As T
Where Exists    (
                Select 1
                From table_name As T2
                Where T2.column_3 = T.column_3
                    And T2.column_1 <> T.column_1
                )

答案 2 :(得分:0)

我还没有在MYSQL中尝试过这个,但是在SQL Server中这个工作。

CREATE TABLE table_name (column_1 CHAR(3), column_2 CHAR(3), column_3 CHAR(3))
INSERT INTO table_name VALUES 
('aaa','bbb','ccc')
,('xys','hkj','fgh')
,('dfs','jhv','ccc')
,('cfg','rty','fgh')
,('iyd','olp','ccc')
,('gdv','tdr','www')

SELECT column_1  
     , column_3 
  FROM table_name a
 WHERE EXISTS(SELECT column_3 
               FROM table_name b
              GROUP BY column_3
             HAVING COUNT(column_3) > 0
                AND b.column_3 = a.column_3)