MySQL: จะเลือกค่าที่แตกต่างจากตารางได้อย่างไร?

ฉันมีตารางขนาดใหญ่ที่มีแถวและคอลัมน์มากมาย แต่ฉันจะอธิบายเฉพาะสิ่งสำคัญเท่านั้น:

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

ข้อมูลตัวอย่าง:

 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

อย่างที่คุณเห็น ดัชนีอยู่ที่ artikel โดยแต่ละ artikel มี name อยู่บ้าง (สำหรับ artikel แต่ละตัวจะมี name เหมือนกัน) และ color ต่างกัน ทุกอย่างเรียบร้อยดี แต่แถว 4 มีปัญหา มีข้อผิดพลาด name = lem on ควรเป็น lemon

ฉันต้องการเลือกแถวเหล่านี้ (GROUP BY artikel) โดยที่ไม่มี name ที่ไม่ซ้ำกัน แต่เป็น HAVING COUNT(name) > 1 ดังนั้นการเลือกของฉันจะกลับมาหนึ่งแถว โดยที่จะเป็น artikel = 2000

ฉันลอง HAVING, DISTINCT แล้ว แต่ไม่สำเร็จ

จะทำแบบนั้นได้อย่างไร?


person Legionar    schedule 25.03.2015    source แหล่งที่มา


คำตอบ (1)


ใช้ group by และ having:

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

คุณยังสามารถใช้ count(distinct) ในส่วนคำสั่ง having ได้อีกด้วย แต่โดยทั่วไปแล้ว count(distinct) ต้องการการทำงานมากกว่าแค่การเปรียบเทียบค่าต่ำสุดและสูงสุด

person Gordon Linoff    schedule 25.03.2015