Multiple condition using “AND” operator and return exact matching rows from a single table using MySQL

穿精又带淫゛_ 提交于 2020-06-24 17:55:12

问题


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.



来源:https://stackoverflow.com/questions/53704761/multiple-condition-using-and-operator-and-return-exact-matching-rows-from-a-si

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!