[英]MySQL Query returning way too many results than it's supposed to
$query = "select DISTINCT user_info.`uid`, company_info.`uid`, user_info.`fname`, user_info.`lname`, user_info.`profile_pic`, company_info.`name` FROM user_info, company_info where fname like '%$q%' or lname like '%$q%' AND company_info.`uid` = user_info.`uid` LIMIT 5";
while($row = mysql_fetch_assoc(mysql_query($query))){
outputUserImage($row["profile_pic"]);
outputUserFname($row["fname"], $row["uid"]);
outputUserLname($row["lname"]);
outputUserCompany($row["name"]);
}
該查詢有效,但是返回的結果太多(重復),執行速度很慢。 有人可以告訴我這是什么問題嗎?
我看到了問題。 您正在循環內反復調用mysql_query()
!
// Don't do this!
while($row = mysql_fetch_assoc(mysql_query($query))){
//-----------------------------^^^^^^^^^^^^^^^^^
相反,請首先在循環外部執行查詢:
// Do the query first
$result = mysql_query($query);
// Check that it succeeded
if ($result) {
// Then fetch rows
while($row = mysql_fetch_assoc($result)){
// Rest of loop...
}
}
// problem with query...
else {
echo mysql_error();
}
您可能正在違反PHP的最大執行時間,否則將導致無限循環,因為您的查詢一遍又一遍地返回。 始終在循環外調用mysql_query()
,並在獲取結果之前驗證它是否已成功完成。
這是因為您的SQL查詢。 您正在執行笛卡爾聯接,只是返回每個表乘以其他行數。
select DISTINCT user_info.`uid`, company_info.`uid`, user_info.`fname`, user_info.`lname`, user_info.`profile_pic`, company_info.`name`
FROM user_info, company_info
where fname like '%$q%'
or lname like '%$q%'
AND company_info.`uid` = user_info.`uid`
LIMIT 5
您想要這樣做,這可以幫助您擺脫與眾不同。 請注意or語句周圍的括號。
select DISTINCT user_info.`uid`, company_info.`uid`, user_info.`fname`, user_info.`lname`, user_info.`profile_pic`, company_info.`name`
FROM user_info, company_info
where company_info.`uid` = user_info.`uid`
and ( fname like '%$q%'
or lname like '%$q%' )
LIMIT 5
我認為這與WHERE子句中的操作順序有關。 AND優先於OR。 嘗試將您的OR'd語句包裝在括號中,如下所示:
where (fname like '%$q%' or lname like '%$q%') AND company_info.`uid` = user_info.`uid` LIMIT 5";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.