mysql - Count in where clause or subquery calculation in select -


i have table story, contains id , title. users can vote or down each story. here model:

+-------+      +----------+ | story |      |   vote   | +-------+~~~~~~+----------+ | id    |      | id       | | title |      | story_id | +-------+      | type     |                +----------+ 

type boolean. fetch stories difference between upvote , downvote > 1. , know how many upvotes story got. sum up, example of result i'm trying get:

+----------+---------+------------+------------+ | story_id | title   | difference | nb_upvotes | +----------+---------+------------+------------+ | 1        | title 1 | 5          | 45         | | 4        | title 4 | 32         | 89         | | 5        | title 5 | 18         | 12         | +----------+---------+------------+------------+ 

i've tried this

select s.id,        s .title,        count(v.id) upvote   story s        inner join vote mp                on v.story_id = s.id                   , v.type = 1  (select count(id)           vote          type = 1                , story_id = s.id) - (select count(id) down                                          vote                                         type = 0                                               , story_id = s.id) > 0 group  s.id;   

but don't difference in results. number of upvotes:

+----------+---------+------------+ | story_id | title   | nb_upvotes | +----------+---------+------------+ | 1        | title 1 | 45         | | 4        | title 4 | 89         | | 5        | title 5 | 12         | +----------+---------+------------+ 

how achieve ?

thanks

edit:

thanks @miken32 got work this

select id, title,     (select count(id) story_moderation story_id = s.id , type = 1) upvotes,     (select count(id) story_moderation story_id = s.id , type = 0) downvotes,     (select count(id) story_moderation story_id = s.id , type = 1) - (select count(id) story_moderation story_id = s.id , type = 0) diff story s having upvotes - downvotes > 0 

but lot of subqueries, isn't resource consuming?

hard without test on, trick? if want capture info in result set, has specified in select clause.

select id, title,     (select count(id) vote story_id = s.id , type = 1) upvotes,     (select count(id) vote story_id = s.id , type = 0) downvotes story s having upvotes - downvotes not in (-1, 0, 1); 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -