MYSQL:SELECT DISTINCT仅显示唯一的行

时间:2014-07-02 11:59:22

标签: mysql sql group-by sql-order-by distinct

我只想看到'Stadt'(= City)列不等于'Hauptstadt'(= Capital)的行。 我的表看起来像:

+----------------------+-------------------+--------------------------+---------------+
| Name                 | Stadt             | Land                     | Hauptstadt    |
+----------------------+-------------------+--------------------------+---------------+
| Kunstmuseum          | Bern              | Schweiz                  | Bern          |
| Musée Picasso        | Paris             | Frankreich               | Paris         |
| Museum Ludwig        | Köln              | Deutschland              | Berlin        |
| Museum of Modern Art | New York          | United States of America | Washington DC |
| Städel               | Frankfurt am Main | Deutschland              | Berlin        |
+----------------------+-------------------+--------------------------+---------------+

我只想看(所需的输出):

+----------------------+-------------------+--------------------------+---------------+
| Name                 | Stadt             | Land                     | Hauptstadt    |
+----------------------+-------------------+--------------------------+---------------+
| Museum Ludwig        | Köln              | Deutschland              | Berlin        |
| Museum of Modern Art | New York          | United States of America | Washington DC |
| Städel               | Frankfurt am Main | Deutschland              | Berlin        |
+----------------------+-------------------+--------------------------+---------------+

我试过这个:

SELECT DISTINCT Name, Stadt, Land ,Hauptstadt 
FROM Museum 
GROUP BY 'Name', 'Stadt', 'Land', 'Hauptstadt' 
ORDER BY Name;

输出:

+----------------------+----------+--------------------------+---------------+
| Name                 | Stadt    | Land                     | Hauptstadt    |
+----------------------+----------+--------------------------+---------------+
| Museum of Modern Art | New York | United States of America | Washington DC |
+----------------------+----------+--------------------------+---------------+

我的SELECT应该如何获得我想要的输出?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

group by中的单引号搞砸了你。首先,只对字符串和日期常量使用单引号。其次,您几乎不需要group byselect distinct。第三,你的病情需要一个where条款。所以试试这个:

SELECT DISTINCT Name, Stadt, Land ,Hauptstadt 
FROM Museum 
WHERE Stadt <> Hauptstadt
ORDER BY Name;

答案 1 :(得分:0)

我们需要按名称对其进行分组,只需比较两列是否相等

SELECT * FROM Museum WHERE Stadt != Hauptstadt GROUP BY Name;