2012-11-22 151 views
0

我有兩個查詢下面,我敢肯定可以合併到一個,但我不知道如何。MYSQL查詢/子查詢合併

我想爲每個用戶獲取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返回文本'None'。

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 

回答

1

使用LEFT JOINCOALESCE顯示的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 

UPDATE 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 
+0

嗨Kuya,謝謝你似乎工作,除了我 – user1052096

+0

..除了它是返回多個記錄存在多個廣告記錄。我只希望它爲每個用戶返回一個記錄。 – user1052096

+0

@ user1052096所以你的意思是任何要顯示的記錄,只要你必須顯示至少1 pettype和petbreed? –