MySQL选择多行等于行

时间:2019-04-18 08:18:20

标签: mysql select where operator-keyword

我有两个表:

TableA          TableB
ID_A            ID_B
P1              Text
P2
P3
P4

TableB
ID_B    Text
1       Bla
2       Blabla
3       Bla bla ecc
4       Bla Bla
5       Bla bla Bla
6       Bla bla bla bla
7       Bla bli

TableA
ID_A    P1  P2  P3  P4
1       5   6   6   6

SELECT ID_A,  P1, P2, P3, P4,
       ID_B, Text
FROM TableA, TableB
WHERE (TableA.P1 = TableB.IDB) OR
      (TableA.P2 = TableB.IDB) OR
      (TableA.P3 = TableB.IDB) OR
      (TableA.P4 = TableB.IDB);

我得到:

ID_A    P1  P2  P3  P4 ID_B Text
1       5   6   6   6   5    Bla bla Bla
1       5   6   6   6   6    Bla bla bla bla

我怎么能得到这个?

ID_A    P1  P2  P3  P4 ID_B Text
1       5   6   6   6   5    Bla bla Bla
1       5   6   6   6   6    Bla bla bla bla
1       5   6   6   6   6    Bla bla bla bla
1       5   6   6   6   6    Bla bla bla bla

我的查询更复杂,我已经总结了问题

1 个答案:

答案 0 :(得分:1)

要执行此操作,您必须从P*的{​​{1}}列构建一个行表。然后可以将其与tableA上的tableA以及各个ID_A值上的tableB相连:

P*

输出(用于我的扩展演示):

SELECT a.*, b.*
FROM (SELECT ID_A, P1 AS P FROM TableA
      UNION ALL
      SELECT ID_A, P2 FROM TableA
      UNION ALL
      SELECT ID_A, P3 FROM TableA
      UNION ALL
      SELECT ID_A, P4 FROM TableA) p
JOIN TableA a ON a.ID_A = p.ID_A
JOIN TableB b ON b.ID_B = p.P
ORDER BY a.ID_A, b.ID_B

Demo on dbfiddle