Select from two tables without repeating data

0

I have two tables, one of users and one of photos where each line contains the user id of the respective photo.

I want to select the user data and get the photos by the user id of the photos table.

In this way it returns me the duplicate data from the user table because the user contains several photos in the photos table.

How can I just get the user data (user table) and all photos that belong to the photos (table photo), which the user ( user_id ) contains in the photos table?

$sql = "SELECT  u.id, u.username, u.genero, u.idade, u.local, u.descricao, p.user_id, p.location 

FROM user AS u 

INNER JOIN photos AS p

ON u.id=p.user_id


";
    
asked by anonymous 04.01.2016 / 19:02

3 answers

3

If what you want to know is the user data and the number of photos that exist for each one, then this SQL should solve:

SELECT  u.id, u.username, u.genero, u.idade, u.local, u.descricao, count(*)
FROM user AS u 
INNER JOIN photos AS p
ON u.id=p.user_id
GROUP BY u.id, u.username, u.genero, u.idade, u.local, u.descricao
    
04.01.2016 / 19:16
2

I am putting an answer because in the comment it will be very bad to do the table that I want to put as an example.

What you are saying is a problem is actually the "right". Let's take a practical example:

User Ricardo has 5 photos:

When doing SQL the return is:

u.id   u.username   p.user_id   p.location
1      Ricardo      1           (local foto1)
1      Ricardo      1           (local foto2)
1      Ricardo      1           (local foto3)
1      Ricardo      1           (local foto4)
1      Ricardo      1           (local foto5)

This is the current result:

What you are asking is to look like this:

u.id   u.username   p.user_id   p.location
1      Ricardo      1           (local foto1)
null   null         1           (local foto2)
null   null         1           (local foto3)
null   null         1           (local foto4)
null   null         1           (local foto5)

That would not be the right one.

If you just want the data from the photos, do a direct SQL in the photos:

select * from photos where user_id = 1

It is not wrong for it to return the duplicate data if you join the two tables.

Do you understand?

    
04.01.2016 / 19:37
0

use select select.

$sql = "SELECT DISTINCT u.id, u.username, u.genero, u.idade, u.local,u.descricao, p.user_id, p.location 

FROM user AS u 

INNER JOIN photos AS p

ON u.id=p.user_id


";
    
04.01.2016 / 19:14