【问题标题】:Getting a wellformed sql-result with habtm relations使用 habtm 关系获得格式良好的 sql 结果
【发布时间】:2011-04-15 05:37:04
【问题描述】:

我需要为 csv 导出编写一个 SQL 查询。我有一个表“商店”,“items_stores”,因此有“项目”。存放 HABTM 物品。现在我想要一个包含项目列的结果。

像这样:

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

希望您能明白这一点。由于我很长时间没有使用原始 SQL,所以我不知道如何做到这一点。该死的ORM。我想到了左连接然后连接左右之类的东西。嗯,目前还没有任何线索,真的。

为简单起见,我们假设表格具有这些字段:

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

数据库是 MySQL 5.x。

【问题讨论】:

  • 您能否更好地了解哪些表中有哪些列?
  • 而您使用的 DBMS 是...
  • 抱歉,添加了更多信息。

标签: sql has-and-belongs-to-many


【解决方案1】:

假设您使用 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 中做到这一点。但我在 SO 上找到了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

【讨论】:

  • 需要对您的代码进行一些调整,然后它就起作用了!太棒了,谢谢。
猜你喜欢
  • 2020-05-12
  • 1970-01-01
  • 2022-10-02
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 2021-12-28
  • 1970-01-01
相关资源
最近更新 更多