检查另一个表中是否存在记录

时间:2013-01-03 07:07:45

标签: mysql sql inner-join

  • 任务; id
  • task_assign; id,task_id
  • task_state; id,assign_id
  • 状态; id,state_id,define_id

enter image description here

我希望包含其他表格中的选定ID

SELECT DISTINCT t.id,t.* FROM tasks AS t
INNER JOIN task_assign AS ta1 ON ta1.task_id=t.id
INNER JOIN task_state AS ts1 ON ts1.assign_id=ta1.id
INNER JOIN states AS s1 ON s1.id=ts1.state_id AND s1.define_id=14
INNER JOIN task_assign AS ta2 ON ta2.task_id=t.id
INNER JOIN task_state AS ts2 ON ts2.assign_id=ta2.id
INNER JOIN states AS s2 ON s2.id=ts2.state_id AND s2.define_id=21
.
.
.
INNER JOIN task_assign AS ta5 ON ta5.task_id=t.id
INNER JOIN task_state AS ts5 ON ts5.assign_id=ta5.id
INNER JOIN states AS s5 ON s5.id=ts5.state_id AND s5.define_id=25

这有效,但当乘法请求减速时。还有另一种方法吗?

1 个答案:

答案 0 :(得分:2)

SELECT
    t.id
FROM
    tasks t
INNER JOIN
    task_assign ta1
    ON ta1.task_id = t.id
INNER JOIN
    task_state ts1
    ON ts1.assign_id = ta1.id
INNER JOIN
    states s1
    ON s1.id = ts1.state_id
    AND s1.define_id IN (14,25)
GROUP BY
    t.id
HAVING
    COUNT(DISTINCT s1.define_id) = 2

编辑 - 向OP解释这是做什么的...... 这将首先检索define_id为14或25的所有记录,但HAVING子句仅允许查询返回具有这两者的那些记录。