代码之家  ›  专栏  ›  技术社区  ›  nocksock

使用habtm关系获得格式良好的sql结果

  •  1
  • nocksock  · 技术社区  · 14 年前

    我需要为csv导出编写一个SQL查询。我有一张表“stores”,“items\u stores”和“items”。存储HABTM项目。现在我想要一个结果,其中包含一列项。

    这样地:

    | Name       | Lat | Lng | Items         |
    | Petes shop | 123 | 123 | Snacks, Pizza |
    | Mama Pasta | 123 | 123 | Pasta, Pizza  |
    

    希望你能明白。由于我很长时间没有使用原始SQL,所以我不知道如何做到这一点。去你妈的。我想到了左连接,然后连接之类的。目前还不知道,真的。

    为了简单起见,假设表中有以下字段:

    Stores: *id, name, lat, lng
    ItemsStores: store_id, item_id
    Items: *id, name
    

    数据库是MySQL 5.x。

    1 回复  |  直到 14 年前
        1
  •  1
  •   Community CDub    8 年前

    假设您使用Sql Server 2005+,我建议您使用以下查询来获取结果表:

    select Name, Lat, Lng, stuff((select ', ' + i.name from item_store ist 
    join item i on ist.itemid = i.id where ist.storeid = s.id for xml path('')), 1,2,'') [Items] from store s
    

    更新。

    我不知道如何在MySql中做到这一点。但我发现 this similar question 就这样。

    我的猜测是:

    select Name, Lat, Lng, gc
    from store s
    join
    (
    select storeid, GROUP_CONCAT(name order by name) gc
    from item_store ist 
    join item i on ist.itemid = i.id 
    where s.id = ist.storeid
    group by storeid
    ) t on t.storeid = s.id