简体   繁体   中英

Mysql - select rows which have linked values

Sorry for the bad title, do not know how to describe it in one sentence.

There is the table:

id, user_id, task_id

I need to select user_ids which have records with several task_id Kind of pseudocode

Select user_id from tasks wherehas task_id = 1 and task_id = 2

As they say, there are many ways to skin a cat. Here is one:

To get a list of users that have multiple tasks assigned, and (at minimum) they have task_id 1 AND task_id 2:

SELECT 
   user_id
FROM user_tasks // or whatever your table is called 
WHERE task_id in (1, 2)
GROUP BY user_id
HAVING COUNT(DISTINCT task_id) = 2

Let us get all the rows where task is is 1 or 2, group them up by user and show only users who have a min task ID that is different to the max task id:

SELECT 
 user_id
FROM t 
WHERE task_id in (1, 2)
GROUP BY user_id
HAVING MIN(task_id) <> MAX(task_id)

You need to appreciate in all of this that when you write a WHERE clause, it is evaluated to be true for every individual row. This means you cannot say WHERE x = 1 AND x = 2 because the value of X can never ever be simultaneously 1 and 2 ON THE SAME ROW.

Instead we use an OR, to get all the user rows that are 1 or 2 and this will give us a mix - some users have multiple rows (the first row is 1 and the next row is 2). Other users have only one row- either a one or a two.

User Task
John 1
Jane 1
Jane 1
Jake 1
Jake 2
Joel 2

When we apply a grouping operation, all those rows are squashed down to one row per user and then things like MIN and MAX can be used and make sense. For a user with only one row his MIN and MAX will be the same number. For a user who had 20 rows that are all value 1, they will also be MIN and MAX the same. Only users who have at least one row that is a 1 and another row that is a 2 will have a different min and max:

User MIN MAX
John 1   1
Jane 1   1
Jake 1   2     <-- the only user HAVING MIN <> MAX
Joel 2   2

Min and max is only really useful in cases where you're looking for 2 different values. In other cases you might look for COUNT DISTINCT that contains the same number as there are elements in the IN list

I think you mean you want the values of user_id for which there is a task with task_id 1 and a task with task_id 2.

Your solution doesn't work because it's looking for a task which has task_id 1 and task_id 2 (which is impossible)

You need:

select a.user_id from tasks a where a.task_id = 1 inner join 
    tasks b where b.user_id = a.user_id and b.task_id = 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM