Select Smallest Value From Multiple Columns with PHP/MySQL

前端 未结 3 842
无人及你
无人及你 2020-12-21 11:47

I have a table set up as the following

ID COL1 COL2 COL3
----------------
10 200  n/a  125
11 150  130  n/a
12 100  300  200
13 500  n/a  n/a
3条回答
  •  有刺的猬
    2020-12-21 12:12

    I suspect using LEAST will result in table scans. You may want to break it down manually (obviously, I expect indexes to be present on COL1, COL2 and COL3):

    SELECT ID, VALUE FROM (
      SELECT ID, COL1 AS VALUE FROM MYTABLE ORDER BY COL1 ASC LIMIT 1
      UNION
      SELECT ID, COL2 AS VALUE FROM MYTABLE ORDER BY COL2 ASC LIMIT 1
      UNION
      SELECT ID, COL3 AS VALUE FROM MYTABLE ORDER BY COL3 ASC LIMIT 1
    ) ORDER BY VALUE ASC LIMIT 1
    

提交回复
热议问题