2014-08-30 47 views
1

我需要在兩個表中選擇外鍵相互匹配,但我不想重複相同的外鍵。SQL SELECT不同的外鍵

我對數據庫中的這些表:

 
    |Photo| (0/*) --------- (1)|Advertisement| 

    |Photo| 
     -photo_id 
     -url 
     -advertisement_id 

    |Advertisement| 
     -advertisement_id 
     ... 

對數據庫中的數據

 
    |Photo| 
     photo_id | url | advertisement_id 
      1 | x |  1 
      2 | x |  1 
      3 | x |  2 
      4 | x |  3 

我想這一點:

 
     ID | URL 
     1 | x 
     2 | x -> It is anyone url 
     3 | x 

我嘗試下面的SQL,但這種重複ID =(

 
    SELECT a.advertisement_id as ID, p.url as URL 
    FROM Advertisement a 
    RIGHT JOIN Photo p 
    ON a.advertisement_id = p.advertisement_id 
    LIMIT 6 

結果:

 
    ID | URL 
    1 | http://i0.statig.com.br/bancodeimagens/18/46/2h/18... 
    2 | http://www.yaves.es/images/Animales/Tiernos-Gatito... 
    2 | http://images.forwallpaper.com/files/thumbs/previe... 
    10 | http://www.petmag.com.br/img/gatos/racas/7892/euro... 
    7 | http://www.gmstatic.com/content/images/1369932859_... 
    8 | http://www.navegandonaweb.com/wp-content/uploads/2... 

任何人都幫我構造SQL查詢?

+0

使用不同的關鍵字ID爲 – Sudarshan 2014-08-30 11:06:29

回答

0
SELECT a.advertisement_id as ID, p.url as URL 
FROM Advertisement a 
RIGHT JOIN Photo p 
ON a.advertisement_id = p.advertisement_id 
GROUP BY a.advertisement_id 
ORDER BY p.photo_id ASC (or DESC ?) 
LIMIT 6 

OR

SELECT a.advertisement_id as ID, p.url as URL 
FROM Advertisement a,Photo p 
WHERE a.advertisement_id = p.advertisement_id 
GROUP BY a.advertisement_id 
ORDER BY p.photo_id ASC (or DESC ?) 
LIMIT 6 
+0

感謝;)工作得很好! – Nbento 2014-08-30 11:21:05