简体   繁体   中英

mysql, count distinct values between two tables

I have two tables

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");

Values in Tables

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

I want the sum of all the names in TableB that correspond in P1, P2, P3, P4

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

Thanks to those who will help me.

You can handle this using UNION ALL and Derived 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

Output

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM