从具有连接和IN的4个表中进行选择

时间:2010-07-29 10:46:27

标签: mysql join subquery

我有5张桌子 首先products喜欢:

id | country_ids | category_ids | users_ids  
1  | 1,4,6       |  4,5,6,70    | 5,6,9  
2  | 5,6,3       |  4,8,2,11    | 1,5,8  

第二个countries喜欢:

c_id | c_name  
1  | Åland Islands  
2  | Antarctica  
...  

第三个categories喜欢:

cat_id | cat_name  
2  | Small  
4  | Large    
...  

第四张表users喜欢:

u_id | u_name  
1  | David  
2  | Mary    
...  

第五个表review(表结构并不重要,只计算id)。

和sql

    SELECT a.*, COUNT(b.comm_id) AS comm_count, c.*, d.*, e.*
    FROM products AS a
    LEFT JOIN comments AS b ON b.comm_prod_id = a.id AND b.comm_published = 1
    LEFT JOIN countries AS c ON c.c_id IN (a.country_ids)
    LEFT JOIN categories AS d ON d.c_id IN (a.category_ids)
    LEFT JOIN users AS e ON e.c_id IN (a.users_ids)
    /*WHERE published = 1*/
    GROUP BY id
    ORDER BY id DESC
    LIMIT 0, 5

但是这个查询只返回连接表的第一个值。

我怎样才能得到像

这样的行
1 | Åland Islands, Equador, Russia | Small, tiny, large, ... | Anna, John, Linda  

PS!或者我是否需要为每个表创建表关系?什么是非常不喜欢的。

1 个答案:

答案 0 :(得分:0)

使用GROUP_CONCAT()函数:

SELECT 
    a.id, 
    GROUP_CONCAT(DISTINCT c_name) AS country_names, 
    GROUP_CONCAT(DISTINCT cat_name) AS cat_names, 
    GROUP_CONCAT(DISTINCT u_name) AS user_names, 
    COUNT(DISTINCT b.comm_id) AS comm_count
FROM products AS a
LEFT JOIN comments AS b ON b.comm_prod_id = a.id AND b.comm_published = 1
LEFT JOIN countries AS c ON c.c_id IN (a.country_ids)
LEFT JOIN categories AS d ON d.c_id IN (a.category_ids)
LEFT JOIN users AS e ON e.c_id IN (a.users_ids)
/*WHERE published = 1*/
GROUP BY id
ORDER BY id DESC
LIMIT 0, 5

更新: 噢,你的桌子上有一个以逗号分隔的列表。它很糟糕。
阅读规范化并使用结构product_comments(product_id,comment_id),product_countries(product_id,country_id)创建关系表,并将每个关系存储在单独的行中。

示例数据:

product_countries  
product_id, country_id  
1, 1
1, 4
1, 6
2, 5
2, 6
2, 3