查询从表中删除行

时间:2015-07-21 22:50:54

标签: sql postgresql

我有两张桌子: datessdeletesssample

我写了一个这样的查询:

DELETE FROM sample
WHERE sample_date_key IN
(SELECT date_key FROM datess WHERE s_date BETWEEN '2015-02-18' and DATE'2015-02-25');

但我在deletess中有2行和2列:

start_date  |  end_date
------------+----------
2015-02-18  | 2015-02-18
2015-01-18  | 2015-01-18

我想删除samplestart_dateend_date之间deletess之间日期的所有行。

我尝试了以下代码,但收到了错误:

  

错误:用作表达式

的子查询返回多行
(SELECT date_key FROM datess WHERE s_date BETWEEN (SELECT start_date FROM deletess) AND (SELECT end_date FROM deletess);

我感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用WHERE EXISTS来检查是否有任何符合条件的行:

DELETE FROM sample
WHERE sample_date_key IN
(
  SELECT date_key
  FROM datess 
  WHERE EXISTS (
    SELECT 1
    FROM deletess
    WHERE s_date BETWEEN start_date
                     AND end_date
  )
);

答案 1 :(得分:0)

join优于in

DELETE s
FROM sample s
INNER JOIN datess d
    ON s.sample_date_key = d.date_key
INNER JOIN deletess sd
    ON sd.start_date <= d.s_date
       AND d.s_date <= sd.end_date;