获取一种且仅有一种类型的记录

时间:2013-02-01 17:27:27

标签: mysql sql select

我坐了几个小时试图解决具体问题,但我无法得到它。最后,我决定在这里发布。以下是一些记录,

╔════════╦════════════╦═════════╦══════════════════╗
║ AUTOID ║ PERSONNAME ║ FLOWER  ║ Other columns... ║
╠════════╬════════════╬═════════╬══════════════════╣
║      1 ║ Alex       ║ Rose    ║                  ║
║      2 ║ Rene       ║ Rose    ║                  ║
║      3 ║ Rene       ║ Jasmin  ║                  ║
║      4 ║ Darwin     ║ Rose    ║                  ║
║      5 ║ Alex       ║ Rose    ║                  ║
║      6 ║ Darwin     ║ Jasmin  ║                  ║
║      7 ║ Alex       ║ Rose    ║                  ║
║      8 ║ Rene       ║ Jasmin  ║                  ║
║      9 ║ Hello      ║ World   ║                  ║
║     10 ║ Hello      ║ World   ║                  ║
╚════════╩════════════╩═════════╩══════════════════╝

我如何得到这个结果,在他/她的所有记录中只有一种花的人

╔════════════╦════════════╗
║ PERSONNAME ║ FLOWERNAME ║
╠════════════╬════════════╣
║ Alex       ║ Rose       ║
║ Hello      ║ World      ║
╚════════════╩════════════╝

我尝试的最好的一个是下面的查询,但仍然无法正常工作。

SELECT  DISTINCT t1.PersonName, t1.Flower
FROM    TableName t1 
        INNER JOIN
        (
            SELECT  personname, COUNT(DISTINCT flower) totals
            FROM    tableName
            GROUP   BY personname, Flower
        )  t2 ON t1.personname = t2.personname and
                    t2.totals = 1

任何想法?

2 个答案:

答案 0 :(得分:4)

您可以对此问题使用GROUP BY子句HAVING子句和COUNT()无需加入子查询

SELECT  PersonName, MAX(Flower) flowerName
FROM    TableName
GROUP   BY PersonName
HAVING  COUNT(DISTINCT Flower) = 1

答案 1 :(得分:0)

或者,因为总是不止一种方法给猫皮肤......

SELECT x.*
  FROM tablename x
  LEFT
  JOIN tablename y
    ON y.personname = x.personname
   AND ((y.flower <> x.flower)
    OR  (y.flower = x.flower AND y.autoid < x.autoid))
 WHERE y.autoid IS NULL;