sql语句中的语法错误

时间:2015-05-05 05:24:42

标签: sql postgresql

我有一个如下所示的sql语句:

delete from survey_results sr
left outer join people p on p.id = sr.person_id
left outer join survey_result_sets srs on srs.id = sr.survey_result_set_id
left outer join survey_schemas ss on ss.id = sr.survey_schema_id
where (sr.person_id is not null and p.id is null)
OR (srs.id is null)
OR (ss.id is null);

但它会出现语法错误:

ERROR:  syntax error at or near "left"
LINE 2: left outer join people p on p.id = sr.person_id

为什么?

2 个答案:

答案 0 :(得分:2)

无法在 PostgreSQL 中的DELETE语句中使用JOIN。而是使用USING并将第二个表放在那里。这样的事情应该有效

   delete from survey_results sr
using people p on p.id = sr.person_id
using  survey_result_sets srs on srs.id = sr.survey_result_set_id
using  survey_schemas ss on ss.id = sr.survey_schema_id
where (sr.person_id is not null and p.id is null)
OR (srs.id is null)
OR (ss.id is null);

您可以参考此PostgreSQL-delete

答案 1 :(得分:1)

怎么样:

begin;
create temp table table_survey_result_pk on commit drop as select survey_result_pk from survey_results sr
left outer join people p on p.id = sr.person_id
left outer join survey_result_sets srs on srs.id = sr.survey_result_set_id
left outer join survey_schemas ss on ss.id = sr.survey_schema_id
where (sr.person_id is not null and p.id is null)
OR (srs.id is null)
OR (ss.id is null);
delete from survey_results t using table_survey_result_pk d on t.survey_result_pk = d.survey_result_pk;
commit;