简体   繁体   English

MySQL:选择“ project_id”等于任何具有特定“ user_id”的“ project”的行

[英]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 . 我有一个表tasks其中行具有列project_id Each project_id refers to (the id of) a row in the projects table. 每个project_id引用projects表中的一行(的id )。 Each project belongs to a certain user which is why it has a column user_id . 每个project属于某个user ,这就是为什么它有一列user_id

I now want to select all tasks from this table where the project_id equals any project of a certain user . 我现在要从此表中选择所有tasks ,其中project_id等于某个user任何project

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. 我想创建一个SELECT语句来接收属于特定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: JOIN表格:

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 SQL小提琴

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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