Welcome!

And don't forget to edit your signature & profile.

 

Icon

Statistics

  • Total posts 26823
  • Total topics 4874
  • Total members 6614
  • Our newest member
    magister

TOP POSTERS

Mysql join 2 tables

All problems and developments related to PHP, Ruby on Rails & Co. are discussed and resolved here.
   

Mysql join 2 tables

Postby MartinD » Tue Sep 08, 2009 7:49 am

Hi all
I have two tables:

Galleries (fields: id, name)
GalleryImages (fields: id, galleryId, imageSrc)

I want to make a list of all galleries, where I also select the imageSrc of ONE image to each gallery. I have tried some join statements, but no matter how I do it, it always returns a row for EACH picture in EACH gallery :? How do I make a correct SQL query for this operation, any ideas?
MartinD
Smashing <frame>
 
Posts: 19
Joined: Wed Feb 11, 2009 12:35 pm
   

   

Re: Mysql join 2 tables

Postby Simon J. » Tue Sep 08, 2009 8:41 am

This should do it:
Code: Select all
SELECT `g`.`id`, `g`.`name`, (SELECT `imageSrc` FROM `GalleryImages` WHERE `galleryId` = `g`.`id` LIMIT 1) AS `image` FROM `Galleries` AS `g`
Simon J.
 
Posts: 8
Joined: Fri Sep 04, 2009 6:28 pm
   

   

Re: Mysql join 2 tables

Postby MartinD » Tue Sep 08, 2009 8:53 am

Great :) That works

However, this is a statement in a statement. Does that affect performance (for the better or for the worse) compared to a join statement?
MartinD
Smashing <frame>
 
Posts: 19
Joined: Wed Feb 11, 2009 12:35 pm
   

   

Re: Mysql join 2 tables

Postby Simon J. » Wed Sep 09, 2009 7:23 am

hmm actually I have no idea. This querry returnes the same result but using JOIN:
Code: Select all
SELECT `g`.`id`, `g`.`name`, `i`.`imageSrc` FROM `Galleries` AS `g` LEFT JOIN (`GalleryImages` AS `i`) ON ( `g`.`id` = `i`.`galleryId`) GROUP BY `g`.`name`

Do some testing, I think this is the best way to figure out wich one is faster.
Simon J.
 
Posts: 8
Joined: Fri Sep 04, 2009 6:28 pm
   


Return to Server-side Scripting



Who is online

Users browsing this forum: No registered users and 2 guests