[英]Joining same table multiple times is throwing error
我有以下mysql代碼
SELECT * FROM `user_credentials`
JOIN `friends` ON `friends`.`1stpal` = `user_credentials`.`cred_regiden`
JOIN `friends` ON `friends`.`2ndpal` = `user_credentials`.`cred_regiden`
WHERE (`cred_fname` LIKE'".$search_text. "%') AND (`friends`.`1stpal` = '$current_user'
OR `friends`.`2ndpal` = '$current_user') LIMIT 0, 5;
我試圖兩次加入表“ friends”,這會引發錯誤:不是唯一的表/別名:“ friends”。 當我將腳本更改為以下內容時,
SELECT * FROM `user_credentials`
JOIN `friends` AS `f1` ON `friends`.`1stpal` = `user_credentials`.`cred_regiden`
JOIN `friends` AS `f2` ON `friends`.`2ndpal` = `user_credentials`.`cred_regiden`
WHERE (`cred_fname` LIKE'".$search_text. "%') AND (`friends`.`1stpal` = '$current_user'
OR `friends`.`2ndpal` = '$current_user') LIMIT 0, 5;
現在顯示: Unknown column 'friends.1stpal'
。 當我運行單聯接時,它運行完美。 但這不是我想要的,我想要兩個表的結果。
在第二個示例中,您仍然使用表格好友,但是應該改用f1或f2。
由於您將表命名為別名f1和f2,因此應在查詢中使用它們:
... ON `f1`.`1stpal` ...
多次連接到同一表時,需要使用表別名(縮寫)。 在整個查詢中都需要使用它們來消除列的歧義:
SELECT *
FROM `user_credentials` uc JOIN
`friends` `f1`
ON f1.`1stpal` = uc.`cred_regiden` JOIN
`friends` `f2`
ON f2.`2ndpal` = uc.`cred_regiden`
WHERE (uc.`cred_fname` LIKE'".$search_text. "%') AND
'$current_user' in (f1.`2ndpal`, f2.`1stpal`)
LIMIT 0, 5;
注意:我在猜測where
子句中的第二個條件。 它可能是:
'$current_user' in (f2.`2ndpal`, f1.1stpal`)
更多評論:
order by
情況下使用limit
可能很危險。 返回的行將匹配,但可能因查詢而異。 in
長於or
長序列(甚至短序列)更容易編寫和理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.