Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何按最后的答复订购?_Sql - Fatal编程技术网

Sql 如何按最后的答复订购?

Sql 如何按最后的答复订购?,sql,Sql,我有两个表格第一个是“用户”第二个是“帖子”, “用户”有两列: 1 id 2 username “帖子”有五栏: 1 p_id 2 uid 3 post_id 4 content 5 date 定义的帖子在post\u id中具有值“0”,回复在post\u id中具有值p\u id。我的问题是 SELECT id,username,p_id,uid,post_id,content,date FROM users inner join posts ON users.id=posts.ui

我有两个表格第一个是“用户”第二个是“帖子”, “用户”有两列:

1 id 
2 username
“帖子”有五栏:

1 p_id
2 uid
3 post_id
4 content
5 date
定义的帖子在
post\u id
中具有值“0”,回复在
post\u id
中具有值
p\u id
。我的问题是

SELECT id,username,p_id,uid,post_id,content,date
FROM users
inner join posts
ON users.id=posts.uid
WHERE post_id='0'
ORDER BY p_id DESC

但我想像在论坛中一样,按最后一次回复排序。

在SELECT子句中使用相关子查询,按该列查找最新回复日期和顺序。如果帖子没有回复,请使用帖子日期:

SELECT id,username,p_id,uid,post_id,content,date, (
    SELECT MAX(date) FROM posts r WHERE r.post_id = p.p_id
) AS last_reply_date
FROM users
inner join posts p
ON users.id=p.uid
WHERE p.post_id='0'
ORDER BY COALESCE(last_reply_date, p.date) DESC

ORDER BY
date
A:RTM=>如果您使用的是mysql。另外,RDBMS不清楚您使用的是哪一个,php标记不包含支持该问题的代码。这里没有php关系,这都是某种SQL。也许吧<代码>按p_id DESC下单应该很容易更改为
日期
但是..更改为日期不起作用..我想在最后一次回复时订购具有值post_id='0'的帖子,例如,当用户回复我的帖子时,我的帖子是最后一篇,帖子将是第一篇