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?
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
) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With