1

假设我有这些表,我需要从中在浏览器中显示搜索结果:

Table: Containers

id   |   name
1      Big Box
2      Grocery Bag
3      Envelope
4      Zip Lock


Table: Sale

id  | date     | containerid
1     20100101   1
2     20100102   2
3     20091201   3
4     20091115   4


Table: Items

id  |  name        | saleid
1      Barbie Doll   1
2      Coin          3
3      Pop-Top       4
4      Barbie Doll   2
5      Coin          4

我需要如下所示的输出:

itemid  itemname     saleids      saledates       containerids     containertypes
1       Barbie Doll    1,2    20100101,20100102       1,2       Big Box, Grocery Bag
2       Coin           3,4    20091201,20091115       3,4       Envelope, Zip Lock
3       Pop-Top         4          20091115            4              Zip Lock

重要的部分是每个项目类型在屏幕上的返回中仅获得一条记录/行。我过去通过返回多行相同的项目并使用脚本语言来限制输出来实现这一点。然而,这使得 ui 过于复杂和循环。所以,我希望我能让数据库只吐出与要显示的行一样多的记录。

这个例子可能有点极端,因为从 item 到容器需要 2 个连接(通过 sale 表)。

我很高兴只是一个输出这个的示例查询:

itemid  itemname     saleids      saledates    
1       Barbie Doll    1,2    20100101,20100102  
2       Coin           3,4    20091201,20091115   
3       Pop-Top         4          20091115       

我只能在子查询中返回一个结果,所以我不知道该怎么做。

4

1 回答 1

3

假设您使用的是 MySQL(在您的四个问题中,只有一个被标记为 MySQL),那么GROUP_CONCAT 函数就是您所追求的:

  SELECT i.name AS itemname,
         GROUP_CONCAT(s.id ORDER BY s.id) AS salesids,
         GROUP_CONCAT(s.date ORDER BY s.date) AS salesdates,
         GROUP_CONCAT(s.containerid ORDER BY s.containerid) AS containerids,
         GROUP_CONCAT(c.name ORDER BY c.name) AS containertypes
    FROM ITEMS i
    JOIN SALE s ON s.id = i.salesid
    JOIN CONTAINERS c ON c.id = s.containerid
GROUP BY i.name

如果您想要可能没有链接到 SALES 和/或 CONTAINERS 表的项目 - 在“JOIN”前面添加“LEFT”。

于 2010-06-16T18:40:59.573 回答