mysql - MySQL JOIN 2 行
问题描述
我有如下表格:
西装
| id | hotel_id | name | etc ...
1 3 Some name
2 3 SomeName2
订单
| id | suits | etc ...
1 1,2
我想从数据库中获取订单列表,其中西装名称如下:
| id | hotel_id | suits | etc ...
1 3 Some name, SomeName2
我正在尝试使用此代码:
SELECT
o.id,
h.name as hotel,
o.hotel as hotel_id,
s.name
FROM h_orders o
LEFT JOIN hotels h ON o.hotel = h.id
LEFT JOIN suits s ON o.suits = s.id
WHERE o.user_id = ? GROUP BY o.id ORDER BY o.id DESC
但只得到第一个西装的名字。我怎样才能得到上面提到的结果?提前致谢。
解决方案
您可以使用以下功能来做到这一点FIND_IN_SET()
:
SELECT
o.id,
h.name as hotel,
h.id as hotel_id,
group_concat(s.name) as suits
FROM h_orders o
LEFT JOIN suits s ON o.suits = s.id
LEFT JOIN hotels h ON o.hotel = h.id
WHERE o.user_id = ? AND FIND_IN_SET(s.id, o.suits)
GROUP BY o.id, h.name, h.id
ORDER BY o.id DESC
o.user_id = ?
尽管您没有解释它需要什么,但我在查询中保留了条件。
推荐阅读
- c++ - 使用 catch2 进行结构和测试的问题
- javascript - 在 jQuery 中使用 setTimeout
- openmdao - 你如何声明数组 wrt 标量的部分,反之亦然?
- rust - delwin 不删除窗口
- css - 有没有办法创建具有类型组合的嵌套有序列表 - HTML + CSS + WordPress?
- typescript - 打字稿中有没有办法将参数限制为对象的键之一,并且该键具有某种类型?
- javascript - 对 npm test 运行 pre 和 post 命令
- adonis.js - 如何使用 find 或 findOrFail 自动加载与 Adonis 的关系?
- python - 如何将两个 ImageSurface 对象合二为一
- apache - http://localhost 正在被转发