我有 2 个 MYSQL 表,firma 和 rach
- 公司表:
id_fir | nazwa | opis | nr_konta | logo ------------------------------------------------- 0 | abc | abc | 123 | img/abc.png 1 | qwerty| qwert | 123 | img/qwerty.png
- rach table:
id_rach | id_fir | data_termin | data_platnosc | kwota ---------------------------------------------------------------- 0 | 1 | 2013-09-30 | null | 123 1 | 0 | 2013-09-30 | 2013-09-17 | 123 2 | 0 | 2013-09-26 | 2013-09-21 | 321 3 | 1 | 2013-09-27 | null | 333
My sql query:
SELECT r.`id_rach` , f.`nazwa` , f.`opis` , r.`kwota` , r.`data_termin` , r.`data_platnosc`
FROM rach r
INNER JOIN firma f
USING ( id_fir )
ORDER BY `data_platnosc` IS NULL asc, `data_termin` desc
到目前为止我做了:
id_rach | nazwa | opis | kwota | data_termin | data_platnosc ----------------------------------------------------------------- 1 | abc | abc | 123 | 2013-09-30 | 2013-09-17 2 | abc | abc | 321 | 2013-09-26 | 2013-09-21 0 | qwerty| qwerty| 123 | 2013-09-30 | null 3 | qwerty| qwerty| 333 | 2013-09-27 | null
我想得到结果:
首先data_platnosc为null和data_termin order desc
然后是其他data_termin顺序描述
id_rach | nazwa | opis | kwota | data_termin | data_platnosc ----------------------------------------------------------------- 0 | qwerty| qwerty| 123 | 2013-09-30 | null 3 | qwerty| qwerty| 333 | 2013-09-27 | null 1 | abc | abc | 123 | 2013-09-30 | 2013-09-17 2 | abc | abc | 321 | 2013-09-26 | 2013-09-21
还有这个解决方案?
我想得到结果:
首先data_platnosc为空,data_termin顺序asc
那么其他data_termin不为null order desc
id_rach | nazwa | opis | kwota | data_termin | data_platnosc ----------------------------------------------------------------- 3 | qwerty| qwerty| 333 | 2013-09-27 | null 0 | qwerty| qwerty| 123 | 2013-09-30 | null 1 | abc | abc | 123 | 2013-09-30 | 2013-09-17 2 | abc | abc | 321 | 2013-09-26 | 2013-09-21
最佳答案
你的order by
几乎是正确的:
ORDER BY `data_platnosc` IS NULL desc, `data_termin` desc
如果您首先想要 NULL
值,则对 order by
的第一个元素使用 desc
。 IS NULL
在为真时返回 1
,而您首先想要它。
或者,你可以用 IS NOT NULL
来表达 is:
ORDER BY `data_platnosc` IS NOT NULL asc, `data_termin` desc
为此:
First data_platnosc is null and data_termin order asc. Then other data_termin is not null order desc
使用case
语句:
ORDER BY `data_platnosc` IS NULL desc,
(case when `data_platnosc` IS NULL then `data_termin` end) asc,
data_termin desc
关于MySQL ORDER BY 一列中的两个 DESC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18746171/