mysql - Conditionally add another column in query base on other query result -


i found solution add query column case when then same table depending on column value can't solve problem.

i have 2 tables. table: pools

    id  date        title           description           ------  ----------  --------------  ---------------------      1  2016-11-10  pool 1  description 

table: votes

    id  date        time      pool_id  option_id  uid                            ------  ----------  --------  -------  ---------  ------------------------------      1  2016-11-10  21:22:23        1          1  xodxfbferdzsofrnbj0aecmgpyo2        2  2016-11-10  21:22:23        1          2  phbz675xdzel59qfklqq8u1uqyg2   

i want query output passing uid in query.

    id  date        title           voted           ------  ----------  --------------  ---------------------      1  2016-11-10  pool 1  yes 

you can left join 2 tables pools , votes. check if corresponding entry exists in votes, show yes else no.

for better explanation, created 1 more entry in pool table.

insert pools values (2, '2016-11-11', 'this pool 2', 'this description'); 

below query give desired output:

select p.id, p.date, p.title, if(v.id not null, 'yes', 'no') voted pools p left join votes v on p.id = v.pool_id , v.uid = 'xodxfbferdzsofrnbj0aecmgpyo2'; 

query explanation

left join return row lhs table , null rhs table if corresponding value not present.

we can add check in select statement create custom column voted.

output

id  date        title          voted ------------------------------------- 1  2016-11-10  pool 1  yes    2  2016-11-11  pool 2  no     

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -