如何在较少的查询中有效地多次为同一个表加入同一个表?

时间:2017-12-22 14:02:58

标签: mysql sql join left-join

我必须在mysql查询中多次加入一个表,我不想为每一列进行左连接。我的表和SQL是 -
table_mst -

id  name    result1 result2 result3
1    A       1       3       3
2    B       2       2       2
3    C       4       4       1
4    D       5       3       2
5    E       2       2       2

store_pick -

id  store_id    pick_id pick_name
1   result       1      pass
2   result       2      fail
3   result       3      supply
4   result       4      grace
5   result       5      ufm

SQL -

 SELECT
  tm.name,
  sp1.pick_name AS result1,
  sp2.pick_name AS result2,
  sp3.pick_name AS result3,
  sp4.pick_name AS result4
FROM table_mst AS tm
  LEFT JOIN store_pick AS sp1
    ON sp1.pick_id = tm.result1
      AND sp1.store_id = 'result'
  LEFT JOIN store_pick AS sp2
    ON sp2.pick_id = tm.result2
      AND sp2.store_id = 'result'
  LEFT JOIN store_pick AS sp3
    ON sp3.pick_id = tm.result3
      AND sp3.store_id = 'result'
  LEFT JOIN store_pick AS sp4
    ON sp4.pick_id = tm.result4
      AND sp4.store_id = 'result'

如何在不使用store_pick表的多个左连接的情况下执行此操作?

1 个答案:

答案 0 :(得分:2)

不需要所有这些连接,您可以使用CASE这样的表达式:

SELECT
  tm.name,
  MAX(CASE WHEN sp1.pick_id = tm.result1 THEN sp1.pick_name END) AS Result1,
  MAX(CASE WHEN sp1.pick_id = tm.result2 THEN sp1.pick_name END) AS Result2,
  MAX(CASE WHEN sp1.pick_id = tm.result3 THEN sp1.pick_name END) AS Result3
FROM Table_mst as tm
LEFT JOIN store_pick AS sp1  ON sp1.store_id = 'result'
GROUP BY tm.name;

您将从原始查询中获得完全相同的结果:

| name | Result1 | Result2 | Result3 |
|------|---------|---------|---------|
|    A |    pass |  supply |  supply |
|    B |    fail |    fail |    fail |
|    C |   grace |   grace |    pass |
|    D |     ufm |  supply |    fail |
|    E |    fail |    fail |    fail |