0

两张表:

任务 - id、creator_id(其余不相关)

tag_tasks - tag_id,task_id

我想通过 tag_tasks 通过标签 id 的数组来获取任务,但也可以获取具有特定 creator_id 的任务。

这是我当前正在执行的语句(不起作用):

SELECT tasks.id, tasks.content
FROM  `tasks` 
JOIN tag_tasks ON tasks.id = tag_tasks.task_id
WHERE (
  `tag_tasks`.`tag_id` 
  IN (1,2,3)
)
OR tasks.creator_id =1
GROUP BY tasks.id
ORDER BY  `tasks`.`id` DESC

这将通过 tag_tasks 表返回任何任务,但忽略在我的连接表中没有记录的任务。

我想要的是一个可以做到这一点的查询:

SELECT tasks.id, tasks.content
    FROM  `tasks` 
    JOIN tag_tasks ON tasks.id = tag_tasks.task_id
    WHERE (
      `tag_tasks`.`tag_id` 
      IN (1,2,3)
    )
    GROUP BY tasks.id
    ORDER BY  `tasks`.`id` DESC;

SELECT tasks.id, tasks.content
FROM tasks
WHERE tasks.creator_id =1
GROUP BY tasks.id
ORDER BY  `tasks`.`id` DESC 
LIMIT 0 , 30

这可能吗?

谢谢你。

4

3 回答 3

2

定期加入将起作用。您想将条件更改为or

SELECT tasks.id, tasks.content
    FROM  `tasks` left outer join
          tag_tasks
          ON tasks.id = tag_tasks.task_id
    where `tag_tasks`.`tag_id` IN (1,2,3) or tasks.creator_id = 1
    GROUP BY tasks.id
    ORDER BY  `tasks`.`id` DESC;

这得到了完整的列表。您可以将其限制为总共 30 个。您真的想要所有“1、2、3”标签以及来自创建者 1 的其他 30 个标签,正如最后两个查询所暗示的那样(但问题中实际上没有提到)?

编辑:

当我查看查询时,我看到您仅在任务级别检索信息。如果您正在寻找具有 1、2 或 3 标签或由 1 创建的请求,我建议使用 have 子句:

SELECT tasks.id, tasks.content
    FROM  `tasks` left outer join
          tag_tasks
          ON tasks.id = tag_tasks.task_id
    GROUP BY tasks.id
    having tasks.creator_id = 1 or sum(tag_id in (1, 2, 3)) > 0
    ORDER BY  `tasks`.`id` DESC;

如果您想修改条件,这使得它更加灵活。例如,如果您想要所有标签或至少两个标签。

于 2013-06-12T18:37:55.573 回答
1

请使用这个:

SELECT tasks.id, tasks.content
FROM  `tasks` 
JOIN tag_tasks ON tasks.id = tag_tasks.task_id
WHERE (
  `tag_tasks`.`tag_id` 
  IN (1,2,3) 
  OR tasks.creator_id =1
)
GROUP BY tasks.id
ORDER BY  `tasks`.`id` DESC
于 2013-06-12T18:38:20.450 回答
1

这是解决我的问题的查询。我只需要创建一个 LEFT JOIN 而不是 JOIN 子句:

SELECT tasks.* 
FROM `tasks` 
LEFT JOIN tag_tasks on tasks.id = tag_tasks.task_id 
WHERE (tag_tasks.tag_id IN (517) OR creator_id = 658) 
GROUP BY tasks.id 
ORDER BY tasks.created_at DESC
于 2013-06-12T20:03:40.490 回答