Mysql CASE WHEN JOIN语句错误

时间:2017-04-16 11:17:52

标签: mysql sql

Mysql查询:

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 

如何解决错误?哪里出错?请帮帮我。

1 个答案:

答案 0 :(得分: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