Thursday 15 September 2011

mysql - SQL: Join and Count based on condition -


I have 2 tables:

  create table items (id INT, name VARCHAR ( 8)); Make Saral Choice (item_id INT, USR VARCHAR (8), likes Boomian); Insert item values ​​(1, 'pen'), (2, 'pencil'), (3, 'ruler'); Values ​​like INSERT (1, 'Joe', true), (1, 'jill', TRUE), (1, 'jack', wrong), (2, 'ja, true), (2,' jill '3', 'MAC', true), (3, 'MAC', false), (3, 'mo'), (2, 'john', true), (3, 'mill', true) 3, 'gill', true), (3, 'jack', wrong);  

Item Likes Pen 2 1 Pencil 2 2 Ruler 3 3

You can use conditional aggregation for this if you select one If you use the SUM (condition) inside the statement, you sometimes get the position that the situation is correct. Use it for your table:

  SELECT i.name, SUM (l.doeslike = true) Select AS, dislike item from SUM (l.doeslike = false). JOIN I like l.item_id = i.id by group i.id;  

Here's an example. I also suggest that if there is an opportunity to present an item without any likes / dislikes, then use a lower joint.


No comments:

Post a Comment