2

例子:

表:盒子

boxID  color
 01     red
 02     blue
 03     green

表:boxHas

boxID  has
 01     apple
 01     pear
 01     grapes
 01     banana
 02     lime
 02     apple
 02     pear
 03     chihuahua
 03     nachos
 03     baby crocodile

我想查询每个盒子的内容,并返回一个包含每个 ID、颜色和连接每个盒子内容的列的表,所以我使用:

SELECT box.boxID, box.color,
GROUP_CONCAT(DISTINCT boxHas.has SEPARATOR ", ") AS contents
FROM box
LEFT JOIN boxHas ON box.boxID=boxHas.boxID
WHERE boxHas.has IN ('apple','pear')
GROUP BY box.boxID
ORDER BY box.boxID

我得到以下结果表:

boxID  color  contents
 01     red    apple, pear
 02     blue   apple, pear

我的问题是:为什么不列出列has中的所有值contents?为什么我的WHERE声明也裁剪了我的GROUP_CONCAT

我想我会得到的桌子是:

boxID  color  contents
 01     red    apple, banana, grapes, pear
 02     blue   apple, lime, pear

虽然我想boxID根据WHERE语句限制我的结果,但我不想限制contents有效框的字段。:-/

帮助?

4

1 回答 1

3

您必须使用 HAVING 子句而不是 WHERE:

SELECT box.boxID
     , box.color
     , GROUP_CONCAT(DISTINCT boxHas.has SEPARATOR ", ") AS contents
  FROM box
  LEFT JOIN boxHas 
    ON box.boxID=boxHas.boxID
 GROUP BY box.boxID
HAVING SUM(boxHas.has IN ('apple','pear')) >= 2
 ORDER BY box.boxID
于 2010-04-05T04:29:14.330 回答