我有这个查询
INSERT INTO subitems_detail (groepid, filiaalid, subitemsid)
SELECT DISTINCT (SELECT id FROM prijsgroepen), 0, subitems.id FROM subitems;
当MySQL
prijsgroepen.id
时,如何创建1
仅插入行的条件?
我试过这样的事情,但是数据库仍会插入行并将0
分配给groepid
,而表格应为空:
INSERT INTO subitems_detail (groepid, filiaalid, subitemsid)
SELECT DISTINCT (SELECT id FROM prijsgroepen WHERE id != 1), 0, subitems.id FROM subitems;
答案 0 :(得分:2)
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值。