根据第二个查询中的时间对两个查询的结果进行排序[关闭]
Posted
技术标签:
【中文标题】根据第二个查询中的时间对两个查询的结果进行排序[关闭]【英文标题】:Order results from two queries based on time in second query [closed] 【发布时间】:2017-05-26 21:29:17 【问题描述】:我需要按时间顺序获取结果,但是因为我在一段时间内使用 sql 查询进入另一个 sql 查询,所以我得到了由$arrID
排序的结果
$req1==mysql_query("SELECT friendId FROM friends ");
while($res1=mysql_fetch_row($req1))
$arrID = $res['friendId'];
$req = mysql_query("SELECT * FROM posts WHERE postby=$arrID ORDER BY posttime DESC ");
while ($res = mysql_fetch_row($req))
echo $res['bostby'];
echo $res['postcontent'];
结果是:
post 1 by 2 content aaaaaaaa time: 11:60
post 2 by 2 content bbbbbbbb time 11:59
post 3 by 2 content aaaaaaaa time: 11:58
post 4 by 2 content bbbbbbbb time 11:56
post 5 by 3 content aaaaaaaa time: 11:61
post 6 by 3 content bbbbbbbb time 11:60
post 7 by 3 content aaaaaaaa time: 11:59
post 8 by 5 content bbbbbbbb time 12:20
post 8 by 5 content bbbbbbbb time 12:19
我需要按时间而不是按 id 排序结果
post 8 by 5 content bbbbbbbb time 12:20
post 8 by 5 content bbbbbbbb time 12:19
post 1 by 2 content aaaaaaaa time: 11:60
post 6 by 3 content bbbbbbbb time 11:60
post 2 by 2 content bbbbbbbb time 11:59
post 7 by 3 content aaaaaaaa time: 11:59
【问题讨论】:
请stop usingmysql_*
functions。 These extensions 已在 php 7 中被删除。了解 PDO 和 @987654325 的 prepared 语句@ 并考虑使用 PDO,it's really pretty easy。
感谢的建议,但你能解决这个问题吗??
并且不要在另一个查询中使用一个查询。请参阅 JOIN。
【参考方案1】:
使用连接两个表的单个查询,而不是执行嵌套循环。
SELECT p.* FROM posts AS p
JOIN friends AS f ON p.postby = f.friendId
ORDER BY p.posttime DESC
从您的评论看来,您的第一个查询并不那么简单。但是你可以加入一个子查询。
SELECT p.* FROM posts AS p
JOIN (
SELECT user_from AS friendId
FROM friend_requests
WHERE user_to = $SessionID AND accepted = '1'
UNION
SELECT user_to AS friendId
FROM friend_requests
WHERE user_from = $SessionID AND accepted = '1'
) AS f ON p.postby = f.friendId
ORDER BY p.posttime DESC
【讨论】:
_有点复杂,其实我用过这个reqq _$reqz="SELECT user_from FROM friend_requests WHERE ( user_to=".$SessionID." AND accepted='1' )UNION SELECT user_to FROM friend_requests WHERE (user_from=".$SessionID." AND accepted='1')"; $resz=mysql_query($reqz); while($rowz=mysql_fetch_row($resz)) $arrID = $rowz[0];
用JOIN (SELECT ... UNION SELECT ...)
替换JOIN friends
**你能帮我修复孔代码吗? :D **
刷新一下就可以看到了。
**OMG :o ** C:\wamp64\www\MY PROJECT\Hometest.php:18:boolean false
以上是关于根据第二个查询中的时间对两个查询的结果进行排序[关闭]的主要内容,如果未能解决你的问题,请参考以下文章
如何根据 ComosDb 中的聚合函数结果对查询结果进行排序?