【问题标题】:Select from 4 tables with joins and IN从 4 个带有连接和 IN 的表中选择
【发布时间】:2011-03-22 15:46:32
【问题描述】:

我有 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 产品作为 LEFT JOIN cmets 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 类别 AS d ON d.c_id IN (a.category_ids) LEFT JOIN users AS e ON e.c_id IN (a.users_ids) /*发布地点 = 1*/ 按 ID 分组 ORDER BY id DESC 限制 0, 5

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

我怎样才能得到这样的行

1 | Åland Islands, Equador, Russia | Small, tiny, large, ... | Anna, John, Linda  

PS!还是我需要为每个表创建表关系?什么很不喜欢。

【问题讨论】:

    标签: mysql join subquery


    【解决方案1】:

    使用 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_cmets(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
    

    【讨论】:

    • 无效 :( 结果我只看到一个结果。例如Åland Islands 而不是Åland Islands, Equador, Russia
    猜你喜欢
    • 2015-04-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    相关资源
    最近更新 更多