MYSQL选择连接 - 在连接上指定唯一值

时间:2013-08-16 21:27:36

标签: mysql select join unique

SELECT T2.ITEM_ID AS item_ITEM_ID 
FROM types T 
  JOIN items T2
    ON T.ITEM_ID = T2.ITEM_PARENT_ID
WHERE T.ITEM_TYPE = 'I' 
 AND T2.ITEM_TYPE = 'I' 

此查询返回T2中具有重复T2.ITEM_PARENT_IDs的行。
如何指定此查询仅返回具有唯一T2.ITEM_PARENT_IDs的行?

1 个答案:

答案 0 :(得分:1)

计算重复次数并在超过1时过滤掉。

SELECT T2.ITEM_ID AS item_ITEM_ID, COUNT(*) dups
FROM types T 
  JOIN items T2
    ON T.ITEM_ID = T2.ITEM_PARENT_ID
WHERE T.ITEM_TYPE = 'I' 
 AND T2.ITEM_TYPE = 'I' 
GROUP BY item_ITEM_ID
HAVING dups = 1

DEMO