0
  • 任务; ID
  • 任务分配;id, task_id
  • 任务状态;id,assign_id
  • 状态; id、state_id、define_id

在此处输入图像描述

我想在其他表中包含选定的 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

这可行,但是当请求增加时它会变慢。还有其他方法吗?

4

1 回答 1

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子句仅允许查询返回同时具有这两者的记录。

于 2013-01-03T07:40:55.093 回答