按行

时间:2017-02-27 12:59:49

标签: mysql

我有来自两张桌子的两个价格,它们已加入。我需要从两个表中按价格排序。当第一个价格为零或为零时,则取第二个价格,否则取第一个价格。所以必须改变部分顺序。

SQL

SELECT table1.id
     , table1.price
     , table2.price FROM table1
  JOIN table2  
    ON table1.id = table2.f_id 
 ORDER 
    BY table1.price ASC
     , table2.price ASC

表1

id / price
1 / 50
2 / 0
3 / NULL
4 / 10

表2

f_id / price
1 / 60
2 / 30
3 / 5
4 / 100

我希望

3 / 5
4 / 10
2 / 30
1 / 50

4 个答案:

答案 0 :(得分:2)

ifnull专为此目的而设计(http://www.mysqltutorial.org/mysql-ifnull/):

SELECT 
   `table1`.id, 
   ifnull(`table1`.price, `table2`.`price`) as finalPrice 
FROM `table1`
  INNER JOIN `table2` ON table1.id = table2.f_id ORDER BY finalPrice ASC

答案 1 :(得分:2)

您也可以使用案例

SELECT table1.id
    CASE WHEN table1.price is null THEN table2.price
         WHEN table1.price = 0 THEN table2.price
         ELSE tabel1.price
    END as my_price
JOIN table2   ON table1.id = table2.f_id 
ORDER BY my_price ASC

答案 2 :(得分:0)

SELECT table1.id
 , table1.price
 , table2.price FROM table1
JOIN table2  
 ON table1.id = table2.f_id 
ORDER BY
  CASE WHEN table1.price is null THEN table2.price
       WHEN table1.price = 0 THEN table2.price
       ELSE tabel1.price
  END ASC

答案 3 :(得分:0)

您可以尝试以下查询

SELECT 
    t1.id,
    CASE
        WHEN t1.price is null THEN t2.price
        WHEN t1.price = 0 THEN t2.price
        ELSE t1.price
    END as finalPrice
FROM
    table1 t1, table2 t2
WHERE
    t1.id = t2.f_id
ORDER BY finalPrice

不使用inner join,而是直接使用t1.id = t2.f_id进行比较。它会更快。