2017-05-26 77 views
-6

我需要,因为使用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 

,我需要的resut是为了通过时间不是由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 
+1

***请[停止使用'mysql_ *'功能](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。* ** [这些扩展](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中删除。了解[prepared](http://en.wikipedia。 org/wiki/Prepared_statement)语句[PDO](http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli .quickstart.prepared-statements.php)并考虑使用PDO,[这真的很简单](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

_ **感谢**的建议,但你能解决这个PLZ ?? _ –

+0

并且不要在另一个查询的时候使用查询。见JOINs。 – Strawberry

回答

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 
+0

_ **这有点复杂,实际上我使用这个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];' –

+0

用JOIN(SELECT ... UNION SELECT ...)替换'JOIN friends''' – Barmar

+0

** _ Can你可以为我修正孔代码!? :D_ ** –