mysql,计算两个表之间的不同值

时间:2019-04-26 07:55:56

标签: mysql count

我有两个桌子

CREATE TABLE TableA  
(ID_A INT,   
P1 INT,
P2 INT,
P3 INT,
P4 INT);

INSERT INTO TableA VALUES
(1,3,4,3,5),
(2,5,4,3,4);

CREATE TABLE TableB
(ID_B INT,
NAME TEXT);

INSERT INTO TableB VALUES
(1,"A"),
(2,"B"),
(3,"C"),
(4,"D"),
(5,"E"),
(6,"F");

表中的值

TableA
+------+----+----+----+-----+
| ID_A | P1 | P2 | P3 | P4  |
+------+----+----+----+-----+
|    1 |  3 |  4 |  3 |   5 |
|    2 |  5 |  4 |  3 |   4 |
+------+----+----+----+-----+

TableB
+------+------+
| ID_B | Name |
+------+------+
|    1 | A    |
|    2 | B    |
|    3 | C    |
|    4 | D    |
|    5 | E    |
|    6 | F    |
+------+------+

tableA P1 = TableB ID_B

tableA P2 = TableB ID_B

tableA P3 = TableB ID_B

tableA P4 = TableB ID_B

我想要TableB中与P1,P2,P3,P4对应的所有名称的总和

+----------+------+
| COUNT(*) | Name |
+----------+------+
|        3 | C    |
|        3 | D    |
|        2 | E    |
+----------+------+

感谢那些会帮助我的人。

1 个答案:

答案 0 :(得分:1)

您可以使用UNION ALLDerived table处理此问题。

select count(*) cnt, name 
from 
(
    select b.name 
    from TableB b
    inner join TableA p1 on p1.p1 = b.id_b
    union all
    select b.name 
    from TableB b
    inner join TableA p2 on p2.p2 = b.id_b
    union all
    select b.name 
    from TableB b
    inner join TableA p3 on p3.p3 = b.id_b
    union all
    select b.name 
    from TableB b
    inner join TableA p4 on p4.p4 = b.id_b
)A
group by name
order by name

输出

cnt         name
----------- --------------------------------------------------
3           C
3           D
2           E

https://www.db-fiddle.com/f/nRpqNiUmpRVJJ4gMP66Ywn/9