来自 table 的 Select 行,按左连接的 ID table

Select rows from table by id of a left join table

我有 3 张桌子:

+-------------+    +-------------+    +-------------+
|    hotel    |    |   hot_cat   |    |   category  |
+------+------+    +------+------+    +-------------+
|  id  | name |    |  hid |  cid |    |  id  | name |
+------+------+    +------+------+    +-------------+
|   1  |   X  |    |   1  |   1  |    |   1  | cat1 |
+------+------+    +------+------+    +-------------+
|   2  |   Y  |    |   1  |   2  |    |   2  | cat2 |
+------+------+    +------+------+    +-------------+
|   3  |   Z  |    |   2  |   2  |    |   3  | cat3 |
+------+------+    +------+------+    +-------------+
                   |   2  |   3  |    |   4  | cat4 |
                   +------+------+    +-------------+
                   |   2  |   4  |
                   +------+------+

我想要 select 类别具有一定价值但所有其他类别都分配给该酒店的酒店。我有这个查询:

SELECT hot.*,GROUP_CONCAT(cat.name SEPARATOR '<br>') AS cats
FROM hotel hot
LEFT JOIN hot_cat hc ON hc.hid = hot.id
LEFT JOIN category cat ON cat.id = hc.cid
WHERE cat.id = 2
GROUP BY hot.id

所以我明白了:

+------+------+-------------------------+
|  id  | name |           cats          |
+------+------+-------------------------+
|   1  |   X  |          'cat2'         |
+------+------+-------------------------+
|   2  |   Y  |          'cat2'         |
+------+------+-------------------------+

我想达到的目标:

+------+------+-------------------------+
|  id  | name |           cats          |
+------+------+-------------------------+
|   1  |   X  |      'cat1<br>cat2'     |
+------+------+-------------------------+
|   2  |   Y  |  'cat2<br>cat3<br>cat4' |
+------+------+-------------------------+

我也希望它在没有 where 子句的情况下工作,并获得没有分配类别的酒店:

+------+------+-------------------------+
|  id  | name |           cats          |
+------+------+-------------------------+
|   1  |   X  |      'cat1<br>cat2'     |
+------+------+-------------------------+
|   2  |   Y  |  'cat2<br>cat3<br>cat4' |
+------+------+-------------------------+
|   3  |   Z  |           ''            |
+------+------+-------------------------+

hot_cat table 开始查询,然后加入 hotel。这是通过 table 的额外跳转,但它解决了问题。

SELECT hot.*,GROUP_CONCAT(cat.name SEPARATOR '<br>') AS cats
FROM hot_cat hc1
LEFT JOIN hotel hot ON hc1.hid = hot.id
LEFT JOIN hot_cat hc ON hc.hid = hot.id
LEFT JOIN category cat ON cat.id = hc.cid
WHERE hc1.id = 2
GROUP BY hot.id

相反,如果您不需要 WHERE,则可以只使用现有查询而不使用 WHERE 子句。