查找mysql中按两列分组的记录

时间:2016-12-20 07:15:49

标签: mysql sql

我想找出所有已经上传产品类别(电子产品,服装,家具)的卖家,因此对于3个类别,每个卖家可以有3行。我有的桌子是

1。category {CATEGORY_ID,名称},

2. seller {seller_id,username},

3。products {PRODUCT_ID,seller_id,CATEGORY_ID,标题}

Note:There can be maximum 3 result (coz I'm searching in 3 categories) against one seller even if he added more than one product in single category

预期结果:

**product_id**        **category**           **sellerUsername**
101                     electronics               kuldeep
211                     furniture                 kuldeep
322                     clothing                  kuldeep
167                     electronics               roman
245                     furniture                 roman
247                     clothing                  dangi
246                     furniture                 dangi
..
..

3 个答案:

答案 0 :(得分:1)

如果只需要匹配关系,请使用内连接

select a.product_id, b.username, c.name
from products as a 
inner join seller as  b on b.seller_id = a.seller_id
inner  join category as c on c.category_id = a.category_id

否则使用左连接

select a.product_id, b.username, c.name
from products as a 
left join seller as  b on b.seller_id = a.seller_id
left   join category as c on c.category_id = a.category_id

答案 1 :(得分:1)

您的问题的一般解决方案是将三个表连接在一起,然后按卖家和类别汇总。在我的解决方案中,我在没有任何逻辑的情况下随意选择了最大产品ID。查询有点棘手,因为我们需要再次将此结果连接到categoryseller表,以获取人类可读的类别和卖家名称。原因是GROUP BY查询理想情况下应该通过ID而不是名称来完成,因为可以想象两个类别(或卖家)可以具有相同的名称但具有不同的ID。

SELECT t3.product_id,
       COALESCE(t1.name, 'NA'),
       COALESCE(t2.username, 'NA')
FROM
(
    SELECT MAX(p.product_id) AS product_id,
           c.category_id,
           s.seller_id
    FROM products p
    LEFT JOIN category c
        ON p.category_id = c.category_id
    LEFT JOIN seller s
        ON p.seller_id = s.seller_id
    WHERE c.name IN ('electronics', 'clothing', 'furniture')
    GROUP BY s.seller_id,
             c.category_id
) t1
LEFT JOIN category t2
    ON t1.category_id = t2.category_id
LEFT JOIN seller t3
    ON t1.seller_id = t3.seller_id

答案 2 :(得分:0)

检查以下代码。

        SET @row_number:=0;
        SET @db_names:= '';
        SET @db_names2:= '';

        select product_id,name as category ,username as sellerUsername
        from (
        select a.product_id,  c.name ,b.username,
               @row_number:=CASE WHEN @db_names=username and @db_names2=name THEN @row_number+1 
               ELSE 1 END AS row_number,@db_names:=username AS username2,@db_names2:=name AS name2
        from products as a 
        left join seller as  b on b.seller_id = a.seller_id
        left join category as c on c.category_id = a.category_id
        where name IN ('electronics', 'clothing', 'furniture') 
        )a where row_number < 2
        order by sellerUsername,name;
  

输出:

enter image description here