1

I got the following tables:

pictures
------------------------------------
id
name
views

votes
------------------------------------
id
user_id
pic_id

I want to get a result from a query that will give me each picture id, with the views of the picture, and the total votes from the table votes for the specific pic_id

example:

pictures.id, pictures.views, total votes

1 ------------ 78------------------ 123

2 ------------ 23------------------- 69

and so on...

The code I tried:

SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes
FROM `pictures` 
JOIN `votes`
ON `pictures`.`id` = `votes`.`pic_id`

But it doesn't give me the reuslt I desire.

4 Answers 4

2

You need to have GROUP BY clause.

The use of LEFT JOIN will display all records on table pictures with or without matching record on table votes.

SELECT  a.id, a.name, a.views,
        COUNT(b.pic_id) TotalVotes
FROM    pictures a
        LEFT JOIN votes b
            ON a.id = b.pic_id
GROUP   BY a.id, a.name, a.views
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! well explained, defenitely solved a problem issue with that LEFT JOIN since I haven't thought about the situation when no one has voted to some picture
1

Use left join with a group function ,normal join keyword means an inner join and you need a left join for one to many relation

SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes
FROM `pictures` 
LEFT JOIN `votes`
ON `pictures`.`id` = `votes`.`pic_id`
GROUP BY `pictures`.`id`

Comments

1

Try this:

SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes
FROM `pictures` 
JOIN `votes`
ON `pictures`.`id` = `votes`.`pic_id`
GROUP BY `votes`.`pic_id`;

Comments

1

You need to try like this using the GROUP BY clause:

SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes
FROM `pictures` 
JOIN `votes`
ON `pictures`.`id` = `votes`.`pic_id`
group by `pictures`.`id`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.