I'm not quite sure if this is the right approach, this is my situation:
I am currently trying to select 15 galleries and then join it using the user table through the id, but I also want to select one random image from each gallery, however from the fact that, as I know, you cannot limit the left connection ( picture) to get only one random image without performing a subquery.
Here is what I got so far, but did not work as it should:
SELECT galleries.id, galleries.name, users.username, pictures.url
FROM galleries
LEFT JOIN users ON users.id = galleries.user_id
LEFT JOIN pictures ON (
SELECT pictures.url
FROM pictures
WHERE pictures.gallery_id = galleries.id
ORDER BY RAND()
LIMIT 1)
WHERE active = 1
ORDER BY RAND()
LIMIT 15
I also tried to do this using Active Recording , but I got stuck after two left joins, is it possible to get a subquery here:
$this->db->select('galleries.id, galleries.name, users.id as user_id, users.username');
$this->db->from('galleries');
$this->db->join('users', 'users.id = galleries.user_id','left');
$this->db->join('pictures','pictures.gallery_id = galleries.id AND','left');
$this->db->where('active',1);
I hope this will not be messy, but I'm really starting to get confused in all sql queries.
:
CodeIgniter