0

我在下面有两个查询,我确定可以合并为一个,但我不确定如何。

我想获取每个用户的 first_name 和 email 列,但我还想从第一条广告记录中获取关联的 pet_type 和 pet_breed(如果他们有的话)。广告记录仅包含一个breed_id,然后将其链接到pet_breeds 表以获取pet_type 和pet_breed。我不需要在结果中返回breed_id,只需要pet_type 和pet_breed。如果用户不存在关联的广告记录,那么我希望 pet_breed 和 pet_type 返回文本“无”。

SELECT users.first_name, users.email,
      (SELECT adverts.breed_id AS breed 
      FROM adverts 
      WHERE adverts.user_id = users.user_id 
      LIMIT 1)
FROM users

第二次查询

SELECT pet_type, pet_breed
FROM pet_breeds
WHERE breed_id = breed
4

1 回答 1

1

使用LEFT JOINand COALESCE(来显示NONE而不是NULL)

SELECT  a.first_name, a.email,
        COALESCE(c.pet_type, 'NONE') pet_type,
        COALESCE(c.pet_breed, 'NONE') pet_breed
FROM    users a
        LEFT JOIN adverts b
            ON a.user_ID = b.user_ID
        LEFT JOIN pet_breeds c
            ON b.breed_ID = c.breed_ID

更新 1

SELECT  a.first_name, a.email,
        COALESCE(c.pet_type, 'NONE') pet_type,
        COALESCE(c.pet_breed, 'NONE') pet_breed
FROM    users a
        LEFT JOIN 
        (
            SELECT user_ID, max(breed_ID) breed_ID
            FROM adverts
            GROUP BY user_ID
        ) b ON a.user_ID = b.user_ID
        LEFT JOIN pet_breeds c
            ON b.breed_ID = c.breed_ID
于 2012-11-22T14:50:39.597 回答