MySQL,动态查询到列的行

时间:2018-07-04 12:39:43

标签: mysql performance pivot-table

我有三个表,名称为employee, employee_products, product_type

enter image description here

引用:http://sqlfiddle.com/#!9/00436/4

我正在尝试获取数据 将此表设为Table_1

使用此查询:

select emp.name, 
(select count(*) from employee_products where product_type_id = 1 and employee_id = emp.id) as Service,
(select count(*) from employee_products where product_type_id = 2 and employee_id = emp.id) as Product,
(select count(*) from employee_products where product_type_id = 3 and employee_id = emp.id) as Other
from employee as emp;

但是,我认为效率不高,我必须从每个新的product_type_id更改此查询,然后才能动态执行此操作。

+------------+---------+---------+-------+--+
| Name       | Service | Product | Other |  |
+------------+---------+---------+-------+--+
| Bezos      | 1       | 0       | 0     |  |
+------------+---------+---------+-------+--+
| Steve      | 0       | 3       | 0     |  |
+------------+---------+---------+-------+--+
| Bill gates | 1       | 0       | 0     |  |
+------------+---------+---------+-------+--+
| Tim Cook   | 0       | 0       | 1     |  |
+------------+---------+---------+-------+--+

和 将此表设为Table_2

在这种情况下,由于mysql中没有数据透视功能,因此我什至无法在mysql中做到这一点。

+------------+---------+---------+---------+---------+-----------+-------+
| Name       | Amazon  | iPhone  | iPad    | iPod    | Microsoft | IDK   |
+------------+---------+---------+---------+---------+-----------+-------+
| Bezos      | Service | NULL    | NULL    | NULL    | NULL      | NULL  |
+------------+---------+---------+---------+---------+-----------+-------+
| Steve      | NULL    | Product | Product | Product | NULL      | NULL  |
+------------+---------+---------+---------+---------+-----------+-------+
| Bill gates | NULL    | NULL    | NULL    | NULL    | PRODUCT   | NULL  |
+------------+---------+---------+---------+---------+-----------+-------+
| Tim Cook   | NULL    | NULL    | NULL    | NULL    | NULL      | OTHER |
+------------+---------+---------+---------+---------+-----------+-------+

请帮助。

注意:product_type, employee_products表中可以有 100 个项目。

2 个答案:

答案 0 :(得分:0)

尝试使用Table_1

Select name, Max(Service) as Service, Max(Product) as Product, Max(Other) as Other
From (
    select e.name, 
            count(case when ep.product_type_id = 1 then 1 else null end) as Service,
            count(case when ep.product_type_id = 2 then 1 else null end) as Product,
            count(case when ep.product_type_id = 3 then 1 else null end) as Other,
    from employee e 
            inner join employee_products ep on (e.id = ep.employee_id)
)
Group by name;

注意:您可以尝试使用Table_2的相同方式

答案 1 :(得分:0)

这里有几段代码可以动态生成和运行SELECT并动态推导各列。 Here是我的。