2017-04-16 199 views
0

MySQL查詢:Mysql的CASE WHEN JOIN語句錯誤

SELECT * 
FROM `pet_info` LEFT JOIN 
    `lostpets` 
    ON `pet_info`.`id` = `lostpets`.`petid` LEFT JOIN 
    `pet_images` 
    ON `pet_info`.`id` = `pet_images`.`petid` 
    CASE WHEN `pet_info`.`pet_cat` = 2 
      THEN LEFT JOIN `cat_breeds` 
       ON `cat_breeds`.`id` = `pet_info`.`pet_breed` 
     WHEN `pet_info`.`pet_cat` = 1 
     THEN LEFT JOIN `dog_breeds` 
       ON `dog_breeds`.`id` = `pet_info`.`pet_breed` 
WHERE `pet_info`.`pet_user_id` = 581 

錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CASE WHEN `pet_info`.`pet_cat` = 2 THEN LEFT JOIN `cat_breeds` ON `cat_breeds`.`' at line 1 

我怎麼能解決錯誤?錯誤在哪裏?請幫幫我。

+2

這根本不是'CASE'所做的。它是一個標量表達式,它在'FROM'子句中返回一個值,而不是一個條件構造。 –

回答

3

我想你打算:

SELECT * 
FROM `pet_info` LEFT JOIN 
    `lostpets` 
    ON `pet_info`.`id` = `lostpets`.`petid` LEFT JOIN 
    `pet_images` 
    ON `pet_info`.`id` = `pet_images`.`petid` LEFT JOIN 
    `cat_breeds` 
    ON `cat_breeds`.`id` = `pet_info`.`pet_breed` AND 
     `pet_info`.`pet_cat` = 2 LEFT JOIN 
    `dog_breeds` 
    ON `dog_breeds`.`id` = `pet_info`.`pet_breed` AND 
     `pet_info`.`pet_cat` = 1 
WHERE `pet_info`.`pet_user_id` = 581; 

注:

  • 有了這樣的查詢,你不應該使用SELECT *,你應該明確地選擇你想要的列。不同的表格具有相同名稱的列。
  • 您應該使用列別名。我沒有把這些放入查詢中,但他們是個好主意。
  • 在真正的查詢中,您將在SELECT中使用表達式來組合cat_breedsdog_breeds的列,例如COALESCE(cat_breeds.col1, dog_breeds.col1) as col1
+0

#1064 - 您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在「pet_info」附近使用正確的語法.'pet_cat' = 1 WHERE'pet_info'.'pet_user_id' = 581第1行限制0,30' –