我正在尝试选择两个(逗号分隔的)项目,一个用于"菜肴和#34;还有一个用于"设施"来自mysql中的4个表。
这是我尝试的方式:
$query = "SELECT GROUP_CONCAT(DISTINCT c.name SEPARATOR ', ') AS cuisines,
GROUP_CONCAT(DISTINCT f.name SEPARATOR ', ') AS facilities
FROM cuisines c, facilities f
INNER JOIN restaurant_cuisines rc ON rc.cuisine_id = c.id
INNER JOIN restaurant_facilities rf ON rf.facility_id = f.id
WHERE rc.restaurant_id = 16 AND rf.restaurant_id = 16";
但是这个查询不起作用。但是如果我对这两个选择使用两个单独的查询,那么我可以让它工作。但我正在寻找单一查询的解决方案。
如果我使用两个单独的查询,这是输出:
mysql> SELECT GROUP_CONCAT(DISTINCT c.name SEPARATOR ', ') AS cuisines
-> FROM cuisines c
-> INNER JOIN restaurant_cuisines rc ON rc.cuisine_id = c.id
-> WHERE rc.restaurant_id = 15;
+-----------------------------------------+
| cuisines |
+-----------------------------------------+
| American, Asian, Bars & Pubs, Beverages |
+-----------------------------------------+
1 row in set (0.14 sec)
任何人都可以告诉我在mysql中是否可能?
谢谢。
答案 0 :(得分:1)
您需要添加GROUP BY语句才能生效:
SELECT cuisines,facilities FROM (
SELECT GROUP_CONCAT(DISTINCT c.name SEPARATOR ', ') AS cuisines, restaurant_id
FROM cuisines c
INNER JOIN restaurant_cuisines rc ON rc.cuisine_id = c.id
WHERE rc.restaurant_id = 16) a
INNER JOIN (
SELECT GROUP_CONCAT(DISTINCT f.name SEPARATOR ', ') AS facilities,restaurant_id
FROM facilities f
INNER JOIN restaurant_facilities rf ON rf.facility_id = f.id
WHERE rf.restaurant_id = 16
GROUP BY rf.restaurant_id) b ON a.restaurant_id=b.restaurant_id;
答案 1 :(得分:1)
不要在from子句中混合,
和inner join
符号它们是两个独立的标准(ANSI与非ANSI),编译器必须选择并使用一个,它可以&#39 ; t两者兼用。换句话说......
FROM cuisines c, <-- This isn't allowed with inner join syntax..
facilities f
INNER JOIN restaurant_cuisines rc ON rc.cuisine_id = c.id
INNER JOIN restaurant_facilities rf ON rf.facility_id = f.id
我改变了连接的顺序,以便美食 - &gt; restraunt_Cusines - &GT; restraunt_facilities - &GT;设施。我认为这是基于符号和连接的准确。我还删除了where子句标准之一,因为它现在基于创建的连接是多余的。
SELECT GROUP_CONCAT(DISTINCT c.name SEPARATOR ', ') AS cuisines,
GROUP_CONCAT(DISTINCT f.name SEPARATOR ', ') AS facilities
FROM cuisines c
INNER JOIN restaurant_cuisines rc
ON rc.cuisine_id = c.id
INNER JOIN restaurant_facilities rf
ON rc.restraunt_Id = Rf.restraunt_ID
INNER JOIN facilities f
ON rf.facility_id = f.id
WHERE rc.restaurant_id = 16;
或
SELECT GROUP_CONCAT(DISTINCT c.name SEPARATOR ', ') AS cuisines,
GROUP_CONCAT(DISTINCT f.name SEPARATOR ', ') AS facilities
FROM cuisines c
,facilities f
, restaurant_cuisines rc
, restaurant_facilities rf
WHERE rc.restaurant_id = 16
AND rf.restaurant_id = 16
AND rc.cuisine_id = c.id
AND rf.facility_id = f.id
但是我相信你错过了restaurant_cuisines和restaurant_facility之间的联接,很可能在restaurant_Id上,这可以让你消除两个rc.restaurant_id = 16
AND rf.restaurant_id = 16