using AND condition MYsql [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-25 06:38:03

问题


What I need is: when I give training_id 172 AND training_id 174 it have to return user 150 only

I tried this but it doen't work

SELECT user_id FROM Training_users WHERE training_id = 172 AND training_id = 174

Most of the times training_id might be more than 2


回答1:


What about this query:

SELECT user_id, COUNT(*) as nbTrainings FROM Training_users
WHERE training_id = 172 OR training_id = 174
GROUP BY user_id
HAVING nbTrainings = 2

It will filter the users having the training 172 or 174. Then it will count how many trainings each user returned has and only keep the one(s) with two trainings.

This supposed that a user cannot have multiple trainings 172 and/or 174

The advantage of this against the multiple self-joins is that you don't have to join multiple times for each training id if you want to filter with more than 2 training id.

More info on GROUP BY and HAVING here

EDIT : After testing in sqlfiddle this seems to work and does not return wrong values if some users have multiple training_id and one being 172 or 174

Working sqlfiddle




回答2:


This should work:

SELECT a.user_id FROM Training_users a, Training_users b WHERE a.training_id = 172 and a.user_id = b.user_id AND b.training_id = 174;



回答3:


This should do it:

SELECT
  a.user_id
FROM
  Training_users a
RIGHT JOIN
  Training_users b ON a.user_id = b.user_id AND b.training_id = 174
WHERE
  a.training_id = 172



回答4:


select user_id from work where training_id in (172,174) group by user_id  having count(*)  > 1;

Check SQLFiddle Demo




回答5:


Do something like this

SELECT user_id FROM Training_users WHERE (training_id = 172) AND (training_id = 174)


来源:https://stackoverflow.com/questions/14936304/using-and-condition-mysql

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