首页 > 解决方案 > 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

但只得到第一个西装的名字。我怎样才能得到上面提到的结果?提前致谢。

标签: mysqlsql

解决方案


您可以使用以下功能来做到这一点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 = ?尽管您没有解释它需要什么,但我在查询中保留了条件。


推荐阅读