MySQL从第2行选择多行

时间:2019-04-23 11:55:48

标签: mysql select union-all

我有两个表:

TableA          TableB
ID_A            ID_B
P1              Text
P2
P3
P4

-

TableB
ID_B    Text
1       A
2       B
3       C
4       D
5       E
6       F
7       G

-

TableA
ID_A    P1  P2  P3  P4
1       7   5   6   6

感谢尼克帮助我 USER Nick

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

我得到:

ID_A    P1  P2  P3  P4    ID_B Text
1       7   5   6   6      5    E
1       7   5   6   6      6    F
1       7   5   6   6      6    F
1       7   5   6   6      7    G

我怎么能得到这个?

ID_A    P1  P2  P3  P4    ID_B Text
1       7   5   6   6      7    G
1       7   5   6   6      5    E
1       7   5   6   6      6    F
1       7   5   6   6      6    F

1°行P1 = ID_B

2°行P2 = ID_B

3°行P3 = ID_B

4°行P4 = ID_B

Demo on db-fiddle

3 个答案:

答案 0 :(得分:1)

您可以将CASEWHEN用于自定义排序顺序。这将以所需的排序显示结果

 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 CASE b.ID_B
     WHEN 7 THEN 4
     WHEN 5 THEN 3
     ELSE 2
 END DESC

enter image description here

答案 1 :(得分:0)

SELECT * FROM TableA as a1
left join TableB as b1 on ID_B = p1
union ALL
SELECT * FROM TableA
left join TableB on ID_B = p2
union ALL
SELECT * FROM TableA
left join TableB on ID_B = P3
union ALL
SELECT * FROM TableA
left join TableB on ID_B = p4

答案 2 :(得分:0)

之所以发生这种情况,是因为派生表中没有(Select Count(*) As cnt From (Select Distinct parent_file_id From [EXAMPLE_TABLE] As tbl)) AS Number_of_parent_files 值的顺序。为了能够进行排序,我们可以添加另一个字段来表示P的数字(例如PP1等),并以此顺序代替P2

ID_B

输出:

SELECT a.*, b.*
FROM (SELECT 1 AS PNUM, ID_A, P1 AS P FROM TableA
      UNION ALL
      SELECT 2, ID_A, P2 FROM TableA
      UNION ALL
      SELECT 3, ID_A, P3 FROM TableA
      UNION ALL
      SELECT 4, 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, p.PNUM

Demo on dbfiddle