插入子查询条件

Insert into subquery condition

我有这个问题

INSERT INTO subitems_detail (groepid, filiaalid, subitemsid)
SELECT DISTINCT (SELECT id FROM prijsgroepen), 0, subitems.id FROM subitems;

如何创建一个条件,使 MySQL 仅在 prijsgroepen.id 而非 1 时插入行?

我尝试过类似的操作,但数据库仍然插入行并将 0 分配给 groepid,而 table 应该为空:

INSERT INTO subitems_detail (groepid, filiaalid, subitemsid)
SELECT DISTINCT (SELECT id FROM prijsgroepen WHERE id != 1), 0, subitems.id FROM subitems;
INSERT INTO subitems_detail (groepid, filiaalid, subitemsid)
SELECT DISTINCT (SELECT id FROM prijsgroepen) As groepid, 0, subitems.id 
FROM subitems
HAVING greopid <> 1
;

这假设 prijsgroepen 中只有一行;否则我很确定查询无论如何都会中断。

子查询 可能 SELECT COUNT(1) FROM prijsgroepen WHERE id != 1 更有用,并将 HAVING 调整为 HAVING greopid = 0

对于每个非一个的一组子项prijsgroepen.id:

INSERT INTO subitems_detail (groepid, filiaalid, subitemsid)
SELECT DISTINCT prijsgroepen.id, 0, subitems.id 
FROM prijsgroepen, subitems
WHERE prijsgroepen.id <> 1
   AND prijsgroepen.id NOT IN (SELECT groepid FROM subitems_detail)
;

AND 行是可选的,以防止重复以前处理的 prijsgroepen.id 值。