2017-05-26 74 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_ ** –