简体   繁体   中英

MySQL: Select rows where `project_id` equals any `project` with specific `user_id`

This can't be too hard, but I don't know what the term is I'm looking for. I'm sure you guys can help me out. :)

I have a table tasks with rows that have a column project_id . Each project_id refers to (the id of) a row in the projects table. Each project belongs to a certain user which is why it has a column user_id .

I now want to select all tasks from this table where the project_id equals any project of a certain user .

Or put more simply:

Each TASK belongs to a PROJECT which belongs to a USER.

I want to create a SELECT-statement to receive all TASKS that belong to a specific USER. The only link between each TASK and a USER is through the PROJECT.

How do I accomplish this?

Thank you very much for your help! :)

JOIN the tables:

SELECT
  t.*
FROM tasks t
INNER JOIN projects p ON t.project_id = p.project_id
INNER JOIN users    u ON p.user_id    = u.user_id
WHERE u.user_id = @AcertianUserId
SELECT
  tasks.*
FROM
  users
INNER JOIN
  projects ON users.id = projects.user_id
INNER JOIN
  tasks ON projects.id = tasks.project_id
WHERE
  users.id = 1

Try :

SELECT t.*
  FROM user u, projet p, task t
 WHERE u.id = p.user_id
   AND p.id = t.project_id
   AND u.id = your_id

Or (same result) :

SELECT t.*
      FROM user u
     INNER JOIN projet p ON u.id = p.user_id
     INNER JOIN task t ON p.id = t.project_id
     WHERE u.id = your_id

SQL Fiddle

select t.*
from tasks t
join projects p on p.id = t.project_id
join users u on u.id = p.user_id
where u.id = 17

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