Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first joined value, not all

Tags:

sql

mysql

I have tables:

'gallery' - information about existing galleries 
id_gallery  name     date
==========  ====  ===========
    1        ...   timestamp

'photo' - information and name of every photo in system
id_photo   photo_name
========   ===========
   1        some name 

'photo_gallery' - "connecting" table, which says which photo are in which gallery
id_photo_gallery   id_photo           id_gallery
================   ================   =================
       1           id from 'photo'    id from 'gallery'

I need to select gallery (with some inforamtion about it, but, that's not important) and only ONE id of photo from 'photo' table.

This (for a big surprise) return all photos. (Duplicated informations about gallery)

SELECT 
    photo_gallery.id_photo as id_photo
FROM
    gallery
        JOIN
    photo_gallery ON gallery.id_gallery = photo_gallery.id_gallery

EDIT

This return only one gallery, not many. I need to retrieve one photo per one gallery ...

SELECT 
    photo_gallery.id_photo as id_photo
FROM
    gallery
        JOIN
    photo_gallery ON gallery.id_gallery = photo_gallery.id_gallery LIMIT 1
like image 234
tomascapek Avatar asked Dec 02 '25 02:12

tomascapek


1 Answers

Please try the following query:

SELECT galery.*, photo.* 
FROM galery
LEFT JOIN photo_gallery ON galery.id = photo_gallery.id_gallery
LEFT JOIN photo ON photo_gallery.id_photo = photo.id
GROUP BY galery.id
like image 93
vidang Avatar answered Dec 03 '25 20:12

vidang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!