Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql join with limit 1

Tags:

sql

mysql

Suppose I have two tables in one to many relationship.

And, I want to select columns from each main record along with the first record from a related table.

I tried some ways but it just doesn't go...

Here I end up with this SQL fiddle:

http://sqlfiddle.com/#!2/39fdb/3

The problem there is that it just cannot reference a.ID from a subselect.

This does not work, of course, but it's just all I could think of

select a.*,b.* from event a left join 
(select * from event_pictures where a.ID=article limit 1)
b on a.ID=b.article;

Any ideas on how to fix it?

like image 971
Anonymous Avatar asked Aug 09 '12 14:08

Anonymous


1 Answers

No, you can't reference a.ID in a subselect that is joined to a. You can do the following, but you better supply an ordering. Otherwise, there is no "first" row. A (more or less) random row from table b will be selected:

select a.*, b.* 
from event a 
  left join event_pictures b
    on b.PK =                        --- the PRIMARY KEY
       ( select bb.PK                --- of event_pictures 
         from event_pictures bb 
         where a.ID = bb.article
         ORDER BY bb.something 
         limit 1
       ) ;
like image 175
ypercubeᵀᴹ Avatar answered Oct 03 '22 21:10

ypercubeᵀᴹ