计算MySql中的多个列

时间:2015-10-07 09:29:34

标签: mysql count

表“orc”

P1        p2       p3         p4
__________________________________
w2        w2       w2         w1
w1        w5       w3         w7

表“artg”

ref      design
_________________
w1        product1
w2        product2  
w3        product3
w4        product4
w5        product5
w6        product6
w7        product7  

我需要计算P1,P2,P3和P4 togheter。

喜欢输出:

Design    Total
_________________
Product1     2
Product2     3

1 个答案:

答案 0 :(得分:0)

使用Union Allorc表的所有列合并为一列。然后找到每个设计的计数并将其与artg表连接。

<强>查询

select t2.design,count(t1.p) as Total 
from
(
    select p1 as p from orc
    union all
    select p2 as p from orc
    union all
    select p3 as p from orc
    union all
    select p4 as p from orc
)t1
right join artg t2
on t1.p = t2.ref
group by t2.design;

<强>结果

+----------+-------+
| Design   | Total |
+----------+-------+
| product1 | 2     |
| product2 | 3     |
| product3 | 1     |
| product4 | 0     |
| product5 | 1     |
| product6 | 0     |
| product7 | 1     |
+----------+-------+