user1260310
user1260310

Reputation: 2227

MYSQL JOIN syntax How to Join Three Tables

The following query does what I want. It returns all the resuls in the users table and then if there is a match in the details tble, returns the relevant data

users

id|username

details

id|userid|firstname|lastname


$sql = "SELECT u.*, d.*
FROM `users` u
LEFT JOIN `details` d on
u.id = d.userid
ORDER BY $strorder";

However, when I try to join an additonal table where I want to do the same thing--return all the results of the users table and if there is a match in the third table, return the relevant data (total followers of this user)--it only returns one record.

3rd table

follow

id|followerid|followedid

$sql = "SELECT u.*, d.*, COUNT(f.id)
FROM `users` u
LEFT JOIN `details` d on
u.id = d.userid
LEFT JOIN `follow` f on
u.id = f.followedid
ORDER BY $strorder";

Can anyone see what I am doing wrong? Thanks in advance for any suggestions.

Many thanks.

Upvotes: 1

Views: 2386

Answers (2)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

Try to avoid * to select fields, it will be clearer to group your datas (even if mysql is quite permissive with groupings).

When you have an aggregate function (like COUNT, SUM), the other "non aggregated" requested fields should be in a GROUP BY clause.

Mysql don't force you to GROUP BY all the fields, but... I think it's quite a good habit to be "as ANSI as possible" (usefull when you use another DBMS)

SELECT u.id, u.username, d.firstname, d.lastname, count(*) as numberfollowers
FROM user u
LEFT JOIN details d on u.id = d.userid
LEFT JOIN follow f on u.id = f.followedid
GROUP BY u.id, u.username, d.firstname, d.lastname --or just GROUP BY u.id with Mysql
ORDER BY count(*) desc

Upvotes: 2

Vikdor
Vikdor

Reputation: 24134

COUNT being an aggregate function, when selected with other columns, requires you to group your results by those other columns in the select list.

You should rewrite your query with columns that you want to select from users and details and group by those columns.

Upvotes: 0

Related Questions