Multiple condition using “AND” operator and return

2020-06-30 06:01发布

问题:

select 
  games_exchange.u_exchange_id 
from 
  games_exchange 
where  
  ( games_exchange.game_id = 7 
  AND games_exchange.exchange_type = 1 )
  AND (
  games_exchange.game_id = 7 
  AND games_exchange.exchange_type = 2 )
group by 
  games_exchange.u_exchange_id 
HAVING 
  COUNT( games_exchange.u_exchange_id ) = 2

My expected result from above query is u_exchange_id = 171. but the above query return u_exchange_id = 171 & 170.

[the screenshot for table is here][2]

回答1:

After a lot of research i came up with a solution to my problem. Actually i was using where condition in a wrong way with having clause. The proposed solution for my problem is given in below code

SELECT u_exchange_id FROM games_exchange 
WHERE 
u_exchange_id IN 
( SELECT u_exchange_id FROM games_exchange WHERE game_id = 7 AND 
exchange_type = 1 )
AND 
u_exchange_id IN 
( SELECT u_exchange_id FROM games_exchange WHERE game_id = 7 AND 
exchange_type = 2)
GROUP BY u_exchange_id 
HAVING COUNT( u_exchange_id ) = 2

Note: I achieved this by using foreach() on games ids of both section and I added dynamically sub-query for every id.