开发者

mysql OR fail to give desired result

开发者 https://www.devze.com 2023-03-25 21:17 出处:网络
Please refer to the 2 tables from the picture below : Code : $query41 = \"SELECTp.message FROM friendship f

Please refer to the 2 tables from the picture below :

mysql OR fail to give desired result

Code :

$query41 = "SELECT  p.message FROM friendship f
JOIN messageslive p
ON p.username = f.frenusername OR p.username = f.username
WHERE f.username = '{开发者_如何学Go$username1}' OR f.frenusername = '{$username1}'
ORDER BY
p.id DESC
LIMIT 16";
$result41 = mysql_query($query41,$connection) or die (mysql_error());
confirm_query($result41);
while($msginfo = mysql_fetch_array($result41)){
        $msg = $msginfo['message'];
        echo $msg . "<br/>";
}

Output :

live
sss
ssa
ddd
asa
(dance2)
asaaa
ssa
(bluek2)
(bluek2)
(bluek2)
(bluek2)
(bluek2)
(bluek2)
(bluek2)
(bluek2)

Question : Why the output show duplicated (bluek2)? How to fix the bug? I want to show the latest 16 posts which are posted by zac1987 and zac1987's friends too. The expected output should look the same as the records in table messageslive, eg :

live
sss
ssa
ddd
asa
(dance2)
asaaa
ssa
(bluek2)
jjj
vv
(comp2)
(sad2)
(dance7)


Do you even need the join to the friendship table?

SELECT p.message
    FROM messageslive p
    WHERE p.username = '{$username1}'
    ORDER BY p.id DESC
    LIMIT 16

If you're just trying to establish existence of a friendship, perhaps:

SELECT p.message
    FROM messageslive p
    WHERE p.username = '{$username1}'
        AND EXISTS(SELECT 1
                       FROM friendship f
                       WHERE f.username = p.username
                           OR f.frenusername = p.username)
    ORDER BY p.id DESC
    LIMIT 16


Change your query to this and it should work.

$query41 = "SELECT  p.message FROM friendship f
JOIN messageslive p
ON p.username = f.frenusername OR p.username = f.username
WHERE f.frenusername = '{$username1}'
ORDER BY
p.id DESC
LIMIT 0, 16";
0

精彩评论

暂无评论...
验证码 换一张
取 消