簡體   English   中英

多次連接同一張表會引發錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM