我需要在两个表中选择外键相互匹配,但我不想重复相同的外键。
我在数据库上有这些表:
|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 :(得分: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