Following on from this question
last_question with this table
`id`, `bbs_id`, `user_id`, `like_dislike`
(15, 4, 2, 0),
(14, 4, 1, 0),
(13, 3, 1, 0),
(12, 2, 1, 1),
(11, 1, 2, 0),
(10, 1, 1, 1);
How can I see what an individual users like or dislike was? Lets say I wanted to have an aggregate table of all the likes and dislikes with another column for whether user x liked it.
This is the query that I have tried
$user_id = 1;
SELECT bbs_id,
(SELECT like_dislike FROM bb_ratings WHERE user_id={$user_id}) AS thisUsersRating,
SUM(CASE WHEN like_dislike = 1 THEN 1 ELSE 0 END) AS likes,
SUM(CASE WHEN like_dislike = 0 THEN 1 ELSE 0 END) AS dislikes
FROM bb_ratings
GROUP BY bbs_id
I guess the problem I am running into here is, how do you refer to user_id = x in this particular row, not in all the rows.
Thanks in Advance
Andrew
I have added an answer to the previous question, please refer to that first, for understanding.
You can’t get it from
bb_ratingsalone by GROUPing it and hacking it. You get Null because you are thinking in terms of a grid, not relational sets (that is the central concept of the Relational Model).Before you decide which table(s) to go to, to service your query, you need to decide what you want for the structure of your result set.
Then constraint it (which rows) with the
WHEREclause.Then figure out where (what tables) to get the columns from. Either joins to more tables, and more work on the
WHEREclause; or scalar subqueries, correlated to the outer query.You are not clear about what you want. It looks like you want the same report as the previous question, plus a column for the given users vote. To me, the structure of your result set is a list of bulletins. Well, I can get that from
bulletin, no need to go tobulletin_likeand then have to GROUP that.If you think in terms of sets, it is very easy, no need to jump through hoops with materialised views or “nested” queries:
Responses to Comments
I have the feeling that what you are saying is very important for how I approach SQL
Yes, absolutely. If you are willing to learn the right stuff up front, it will:
.
For now, forget about using result sets as tables (much slower), and temp tables (definitely not required if your database is Normalised). You are much better off querying the tables directly. You need to learn various subjects such as the Relational model; how to use SQL; how not to use SQL so as to avoid problems; etc. I am willing to help you, and stay with you for a while, but I need to know you are willing. It will take a bit of back-and-forth. There is a bit of noise on this site, so I will ignore other comments (until the end) and respond only to yours.
GROUP BY, it is seriously hindering your understanding of SQL. If you can't get the report you want without usingGROUP BY, ask a question..
This posted question. Let me know at which point you got lost, and I will provide more detail from that point forward.
.