简体   繁体   中英

MYSQL: SELECT DISTINCT only show rows which are unique

I only want to see the rows where the column 'Stadt'(=City) isn´t equal to 'Hauptstadt'(=Capital). my table looks like:

+----------------------+-------------------+--------------------------+---------------+
| 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        |
+----------------------+-------------------+--------------------------+---------------+

I only want to see(desired output):

+----------------------+-------------------+--------------------------+---------------+
| 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        |
+----------------------+-------------------+--------------------------+---------------+

I tried it this:

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

Output:

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

How should my SELECT look like to get my desired ouput?

Thanks for your help!

The single quotes in the group by are messing you up. First, only use single quotes for string and date constants. Second, you almost never need group by with select distinct . Third, you need a where clause for your condition. So try this:

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

我们需要按名称分组,如果相等或不相等,则只比较两列

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

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