php - Check if a user has voted for the maximum number of items he can vote for -


table items

id  maxvotes    parent      type 10  2           9           heading  11  0           10          item 12  0           10          item 

table votes

userid  votedfor parent 1       11       10  1       12       10 2       12       10 

i'm trying check if item exists, , if user has voted maximum number of items permitted under heading.

in example above, table items contains items. table votes contains votes cast users.

table items type : heading specifies maximum number of items user can vote col : maxvotes. in case, it's 2.

in table votes user 1 has voted on 2 items , can vote no more items under heading. user 2 can vote 1 item more.

it goes on that.

the way current (using php), to:

select id, parent items id = 11 //the item exists.

select maxvotes items id = parent // gives me maximum items user can vote for.

select count(votedfor) votes votes userid = 1 // this'll give me 2.

user 1 can vote no more, user 2 can vote once more -> add vote votes table

can think of easier, more efficient , sophisticated way this, other way above?

i can make changes things since still isn't implemented. or, best way?

your design okay is, can combine steps in 1 query.

select  userid votes # not exists (select 1 votes sv sv.userid = votes.userid #                   , votedfor = 11) group userid having count(*) < (   select   max(i2.maxvotes)     items i1   inner join items i2 on i1.parent = i2.id     i1.id = 11 /*here choose item*/ ) 

this query give users can still vote. uncomment where not exists part exclude users haven't reached vote limit have voted item checking.

see working live in sqlfiddle.

update:

select  case when numberofvotes >= maxvotesforitem 'has reached vote limit'      else concat('user has ', maxvotesforitem - numberofvotes, ' vote left') end result /*optionally include...*/ #, numberofvotes, maxvotesforitem (   select   count(*) numberofvotes   , (select      max(i2.maxvotes)           items i1      inner join items i2 on i1.parent = i2.id           i1.id = 11 /*here choose item*/   ) maxvotesforitem     votes      userid = 2 /*here choose user*/ ) sq 

again sqlfiddle.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -