我遇到了一些mysql查询问题。表结构如下:
+----+--------+---------------------+
| id | parent | datetime |
+----+--------+---------------------+
| 1 | null | 2014-03-01 09:14:02 |
| 2 | 1 | 2014-03-01 09:38:32 |
| 3 | 1 | 2014-03-01 09:45:52 |
| 4 | 2 | 2014-03-01 09:42:23 |
| 5 | null | 2014-03-01 09:47:42 |
| 6 | null | 2014-03-01 09:33:01 |
| 7 | 5 | 2014-03-01 09:54:39 |
+----+--------+---------------------+
我希望父母按日期时间排序,如果有任何孩子按日期时间排序,则需要2级结果。数据将列出如下:
+----+--------+------------------------+
| id | parent | datetime |
+----+--------+------------------------+
| 1 | null | 2014-03-01 09:14:02 |
| 2 | 1 | 2014-03-01 09:38:32 |
| 4 | 2 | 2014-03-01 09:42:23 |
| 3 | 1 | 2014-03-01 09:45:52 |
| 5 | null | 2014-03-01 09:47:42 |
| 7 | 5 | 2014-03-01 09:54:39 |
| 6 | null | 2014-03-01 09:33:01 |
+----+--------+------------------------+
我可以按日期时间订购父母,孩子介于两者之间,但不是按日期时间(子女)。
答案 0 :(得分:1)
使用UNION ALL
,您可以先选择父母,然后选择所有孩子。在两个联合查询中,您可以选择额外信息来帮助您排序。在这种情况下,我引入了一个类型(1是父项,2是孩子)和orderdatetime
,它基本上是孩子的父项的日期时间。
SELECT
x.id,
x.datetime
FROM
(SELECT
p.id,
p.datetime,
1 AS itemtype,
p.id as sortparent,
p.datetime AS sortdatetime
FROM
YourTable p
WHERE
p.parent IS NULL
UNION ALL
SELECT
c.id,
c.datetime,
2 AS itemtype,
c.parent as sortparent,
p.datetime AS sortdatetime
FROM
YourTable p
INNER JOIN YourTable c ON c.parent = p.id) x
ORDER BY
x.sortdatetime,
x.sortparent
x.itemtype,
x.datetime
对于排序,我排序:
答案 1 :(得分:0)
可以将“datetime”保存为time()
吗?
+----+--------+------------------------+
| id | parent | datetime |
+----+--------+------------------------+
| 1 | null | 1388615716 |
| 2 | 1 | 1388697666 |
| 4 | 2 | 1388790487 |
| 3 | 1 | 1388952461 |
+----+--------+------------------------+
并排序ORDER BY datetime
。