Mysql - joins - too many rows are being returned - one for each of the joined table but dont want that

StackOverflow https://stackoverflow.com/questions/10442271

  •  05-06-2021
  •  | 
  •  

Question

I have this kind of mysql db (table name/fields)

tbl_users: id, title, approved

tbl_photos: id, user_id, title, filename

I have one row in users, and three photos (all with user_id = the id of the user)

doing this:

select 
tbl_users.*, 
tbl_photos.filename 

from tbl_users 

left join tbl_photos on tbl_photos.user_id = tbl_users.id 

where tbl_users = '1' order by rand() 

(table query simplified a little bit)

doing that sql query returns three rows . I only want one row (ie i want the user row, plus any random photo that has the user_id of that user id)

i've tried all joins - left right inner but they always return 3 rows

Was it helpful?

Solution

Your code should be like the following

select 
tbl_users.*, 
tbl_photos.filename 

from tbl_users 

left join tbl_photos on tbl_photos.user_id = tbl_users.id 

where tbl_users = approved order by rand() LIMIT 1

The LIMIT keyword will restrict the query for returning only 1 row.

A simple list of my-sql command examples can be found here http://itswadesh.wordpress.com/2011/04/12/mysql-commands/

OTHER TIPS

you also add DISTINCT:

select  DISTINCT tbl_users.id, 
        tbl_users.title, 
        tbl_users.approved, 
        tbl_photos.filename 
from tbl_users left join tbl_photos 
       on tbl_photos.user_id = tbl_users.id 
where tbl_users = 'approved' order by rand() 

It is very simple if you want to get only one row for each do it like this

select 
tbl_users.*, 
GROUP_CONCAT(tbl_photos.filename) as Photos

from tbl_users 

left join tbl_photos on tbl_photos.user_id = tbl_users.id 

where tbl_users = '1' order by rand() 

It will give you comma seperated values in a single field

If filename is the only field you will retrieve from tbl_photos, this could deliver what you need:

select 
    tbl_users.*, 

    (select filename 
     from tbl_photos where user_id = tbl_users.id 
     order by rand()
     limit 1) as filename

from tbl_users 

If you want other information from photos, this is the query:

select tbl_users.*, 'x' as separator, tbl_photos.*
from tbl_users
left join tbl_photos on tbl_photos.user_id = tbl_users.id
where (tbl_users.id, tbl_photos.id) in

    (  
    -- you can run this query independently
        select 

            id, 

            (select id 
             from tbl_photos 
             where user_id = tbl_users.id 
             order by rand() 
             limit 1) 

        from tbl_users
    )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top