mysql order case,MYSQL ORDER BY CASE问题

I have a database like this:

-------------------------------------------------------------------

| id_one | id_two | timestamp_one | timestamp_two |

-------------------------------------------------------------------

| 27 | 35 | 9:30 | NULL |

-------------------------------------------------------------------

| 35 | 27 | NULL | 9:35 |

-------------------------------------------------------------------

| 27 | 35 | 9:34 | NULL |

-------------------------------------------------------------------

| 35 | 27 | NULL | 9:33 |

-------------------------------------------------------------------

I need pull all 4 rows

ORDER BY 'timestamp_one' if 'id_one'=27 or

ORDER BY 'timestamp_two' if 'id_one'=27

This is the statement I have now:

SELECT * FROM tablename

WHERE id_one=27 OR id_two=27

ORDER BY

CASE WHEN id_one=27 THEN timestamp_one END DESC,

CASE WHEN id_two=27 THEN timestamp_two END DESC

This works good in that is outputs this:

-------------------------------------------------------------------

| id_one | id_two | timestamp_one | timestamp_two |

-------------------------------------------------------------------

| 27 | 35 | 9:30 | NULL |

-------------------------------------------------------------------

| 27 | 35 | 9:34 | NULL |

-------------------------------------------------------------------

| 35 | 27 | NULL | 9:33 |

-------------------------------------------------------------------

| 35 | 27 | NULL | 9:35 |

-------------------------------------------------------------------

But I need to two timestamp columns to order like they are one so it would order like this:

-------------------------------------------------------------------

| id_one | id_two | timestamp_one | timestamp_two |

-------------------------------------------------------------------

| 27 | 35 | 9:30 | NULL |

-------------------------------------------------------------------

| 35 | 27 | NULL | 9:33 |

-------------------------------------------------------------------

| 27 | 35 | 9:34 | NULL |

-------------------------------------------------------------------

| 35 | 27 | NULL | 9:35 |

-------------------------------------------------------------------

I hope this makes sense. Essentially, I am trying to have two ORDER BY columns that are specific to a WHERE condition. Then once the correct ORDER BY column is chosen for that row, it orders the ROWS by the timestamp as a whole.

解决方案SELECT id_one, id_two, timestamp_one, timestamp_two

FROM tablename

WHERE id_one = 27

OR id_two = 27

ORDER BY

CASE

WHEN id_one=27 THEN timestamp_one

WHEN id_two=27 THEN timestamp_two

END DESC

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值