postgresql子选择结果中的任意一个

puruo6ea  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(377)

我正在尝试编写以下查询:

SELECT DISTINCT t.* FROM tasks t  WHERE (769, 2) IN 
  (SELECT c3.id FROM categories c3 JOIN tasks_categories tc ON c3.id = tc.category_id WHERE tc.task_id = t.id)

但它失败了,错误如下:

ERROR: subquery has too few columns

看起来原因是我在检查 (769, 2) 在子查询的结果中。如何重写此查询以检查:

ANY of (769, 2) in the result of (subselect) ?
tpgth1q7

tpgth1q71#

你可以用 exists . . . 可能不需要 select distinct :

SELECT t.*
FROM tasks t
WHERE EXISTS (SELECT 1
              FROM categories c3 JOIN
                   tasks_categories tc
                   ON c3.id = tc.category_id
              WHERE tc.task_id = t.id AND c3.id IN (769, 2)
             );
``` `SELECT DISTINCT` 只会带来额外的开销——假设这样的话,就不需要了 `tasks` 没有重复的行。
dgiusagp

dgiusagp2#

你必须用下面的格式重写查询,

SELECT DISTINCT t.* FROM tasks t
JOIN tasks_categories tc ON (tc.task_id = t.id)
JOIN categories c3 ON (c3.id = tc.category_id)
where  c3.id in (769, 2);

相关问题