简体   繁体   English

MySQL:如何从表中选择不同的值?

[英]MySQL: How to select distinct values from a table?

I have huge table with many rows and columns, but I will describe only important of them: 我有很多行和列的大表,但我只会描述它们中的重要部分:

+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name      | varchar(255)     | NO   |     | NULL    |                |
| artikel   | int(10) unsigned | NO   | IDX | NULL    |                |
| color     | varchar(255)     | NO   |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+

Example data: 示例数据:

 1    apple        1000      red
 2    apple        1000      yellow
 3    lemon        2000      blue
 4    lem on       2000      green
 5    lemon        2000      black
 6    apple        1000      white
 7    cherry       3000      lime
 8    cherry       3000      pink
 9    lemon        2000      silver
10    apple        1000      gold

As you can see, the index is on artikel , each artikel has some name (for each artikel there is the same name ) and different color . 如你所见,索引在artikel ,每个artikel都有一些name (每个artikel有相同的name )和不同的color Everything is OK, but with row 4 there is problem, there is wrong name = lem on , it should be lemon . 一切都还可以,但是第4行有问题,有错误的name = lem on ,它应该是lemon

I want to select these rows ( GROUP BY artikel ), where there is not unique name , but HAVING COUNT(name) > 1 . 我想选择这些行( GROUP BY artikel ),其中没有唯一的name ,但是HAVING COUNT(name) > 1 So my select will return one row, where will be artikel = 2000 . 所以我的选择将返回一行,其中将是artikel = 2000

I tried HAVING , DISTINCT , but with no success. 我试过HAVINGDISTINCT ,但没有成功。

How can be done that? 怎么办?

Use group by and having : 使用group byhaving

select artikel
from exampledata
group by artikel
having min(name) <> max(name);

You can also use count(distinct) in the having clause. 您还可以在having子句中使用count(distinct) But count(distinct) typically requires more work than just comparing the minimum and maximum values. 但是count(distinct)通常比仅仅比较最小值和最大值需要更多的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM