Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select SQL one row more

Tags:

sql

mysql

I have a site with a database with user, I have three simple table:
- users
- user_profile (with an external key called: user_id to table users)
- user_image_profile (with an external key called: user_id to table users)

I want to select simply with a join this three table with the external key user_id.

Into my database there are three users, but when I run it retrieve me 4 users! one more than the users into the database, the repetaed user is the first.

Every user has a row into the tables users, user_image_profile and user_profile Only a user doesn't have the row into user_image_profile.

I don't understand why return me 4 instead of three users.

SELECT *, `users`.`id` as user_id
FROM (`users`)
LEFT JOIN `user_profile` ON `user_profile`.`user_id` = `users`.`id`
LEFT JOIN `user_image_profile` ON `user_image_profile`.`user_id` = `users`.`id`
ORDER BY `users`.`created` desc LIMIT 12 
like image 566
Alessandro Minoccheri Avatar asked Feb 04 '26 11:02

Alessandro Minoccheri


1 Answers

I think you need an INNER JOIN rather than a LEFT JOIN query

SELECT *, `users`.`id` as user_id 
FROM (`users`) 
INNER JOIN `user_profile` 
ON `user_profile`.`user_id` = `users`.`id` 
INNER JOIN `user_image_profile` 
ON `user_image_profile`.`user_id` = `users`.`id` 
ORDER BY  `users`.`created` desc LIMIT 12 
like image 74
Fabio Avatar answered Feb 06 '26 23:02

Fabio