如何连接表和2选择

时间:2015-07-08 21:24:55

标签: mysql

我有以下两个问题,如何将它们连接在一起?

查询1:

SELECT product_name, count(product_name) as count_product_name
FROM ps_order_detail
WHERE id_shop = 1
group by product_name
order by count_product_name DESC
LIMIT 5

QUERY2:

SELECT count(*) as count, concat(decade, '-', decade + 9) as year
FROM (SELECT floor(year(`birthday`) / 10) * 10 as decade
      FROM ps_customer) C
GROUP BY decade;

第一个查询是获取最多订购的前5个产品名称。

第二个查询是获取客户生日年份,并按每十年分组一次。

我想知道订购前5名产品的年龄组。

结果应该是

product name, years, count
productA 1990-2009  100
ProductA 2000-2019  20
ProductB 1980-1999  20
ProductB 1990-2009  25
ProductB 2000-2019  20

...

我确实有第三张表来连接。

create table ps_orders(
  id_customer,
id_order
);

create table ps_customer(
id_customer, birthday
);
create table ps_order_detail(
id_order, product_name
);

我不知道如何把它们放在一起,我可以逐一输入产品名称来获得这些年份。

SELECT count(*) as count, concat(decade, '-', decade + 9) as year 
FROM (SELECT floor(year(birthday) / 10) * 10 as decade 
      FROM ps_customer as CU, 
           ps_orders as O, 
           ps_order_detail as OD 
      WHERE CU.id_customer = O.id_customer 
        AND O.id_order = OD.id_order 
        AND OD.product_name = 'product Name A' 
    ) C    
GROUP BY decade;

1 个答案:

答案 0 :(得分:1)

使用您的第二个查询,但不是指定特定产品,而是将其放入分组中。然后将其与返回前5个产品的子查询联系起来以限制它。

{0:$###,###,###,###,###,###,###,###.##############}