MySQL查询参考多对多表

时间:2018-03-28 14:47:41

标签: mysql database

假设有以下表格:

// "app_non_users" will list friends that haven't installed the game yet
List<object> filter = new List<object>() { "app_non_users" };
// Then, call the API with this filter. Enjoy!
FB.AppRequest("Test Message", null, filter, null, 0, string.Empty, string.Empty, this.HandleResult);

以下查询非常接近正确答案,但不正确。你能告诉我们正确的查询是什么吗?

area
-id
-title

properties
-id
-title
-area_id

categories
-id
-title

properties_categories
-property_id
-category_id

OR

select a.id, a.title, count(p.id) 
FROM area AS a,properties AS p, properties_categories AS pc 
WHERE a.id = p.area_id 
  AND pc.category_id IN (1,2,3) 
  AND pc.property_id = p.id 
GROUP BY a.id;

如果我编写一个查询,其中以下内容仅从区域和属性表中绘制,那么您将获得正确的结果。

SELECT A.id, A.title, COUNT(B.id)
FROM area A LEFT JOIN  properties B 
ON A.id=B.area_id 
JOIN properties_categories C 
ON C.property_id=B.id
WHERE C.category_id IN (1,2,3)
GROUP BY A.id, A.title;

以下是要试验的数据转储:

SELECT A.id, A.title, COUNT(B.id) FROM area A LEFT JOIN properties B ON A.id=B.area_id GROUP BY A.id, A.title

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT A.id, A.title, COUNT(B.id)
FROM area A LEFT JOIN  properties B 
ON A.id=B.area_id 
JOIN properties_categories C 
ON C.property_id=B.id
WHERE C.category_id IN (1,2,3)
GROUP BY A.id, A.title;

有关在mysql中使用连接的见解,请参阅MySQL Join Made Easy