I have two tables user and task as follows:
user:
task:
I need to query to get all the user ids of the task id whose user is 2 and the output table should be:

Can anybody help me with the query? Thanks in advance.
Use the GROUP_CONCAT function:
SELECT
t.task_id AS task_id,
GROUP_CONCAT(t.user_id) AS user_id,
GROUP_CONCAT(u.username) AS user
FROM task t
JOIN user u ON t.user_id = u.id
WHERE EXISTS (
SELECT 1 FROM task
WHERE task.task_id = t.task_id AND task.user_id = 2
)
GROUP BY t.task_id