mysql插入值选择不存在

时间:2013-12-26 09:37:39

标签: php mysql select insert mysqli

如何完成这项工作我在INSERT中阻止了loop? 我得到sql error code 1093,这是数组结果:

INSERT INTO kelengkapan_berkas (id_buyer, nama_berkas) VALUES

('1', (SELECT jenis_berkas.nama_berkas FROM jenis_berkas WHERE id_job = '1' AND NOT EXISTS (SELECT id_buyer FROM kelengkapan_berkas WHERE id_buyer = '1'))),

('2', (SELECT jenis_berkas.nama_berkas FROM jenis_berkas WHERE id_job = '1' AND NOT EXISTS (SELECT id_buyer FROM kelengkapan_berkas WHERE id_buyer = '2'))),

('3', (SELECT jenis_berkas.nama_berkas FROM jenis_berkas WHERE id_job = '1' AND NOT EXISTS (SELECT id_buyer FROM kelengkapan_berkas WHERE id_buyer = '3')))

我的循环代码工作但我需要避免因为XD的连接:

    while($rows=mysqli_fetch_array($res)){
    $sql="INSERT INTO kelengkapan_berkas 
               (id_buyer, nama_berkas) 
          SELECT    '$rows[id]', 
              jenis_berkas.nama_berkas 
          FROM jenis_berkas 
          WHERE id_job = '$rows[job]' AND NOT EXISTS 
             (SELECT * FROM kelengkapan_berkas WHERE id_buyer = '$rows[id]')";
    $result=mysqli_query($con,$sql);}

或任何想法用触发器或程序执行此操作? THX

4 个答案:

答案 0 :(得分:2)

此限制记录在MySQL manual

Currently, you cannot update a table and select from the same table in a subquery.

作为一种变通方法,您可以将子查询包装在另一个子查询(嵌套)中并避免该错误。

INSERT INTO kelengkapan_berkas (id_buyer, nama_berkas) VALUES 
('1', (SELECT NAME (SELECT jenis_berkas.nama_berkas NAME FROM jenis_berkas WHERE id_job = '1') ,.....

答案 1 :(得分:0)

表设计。

使ID买家成为唯一索引并在代码中捕获异常。

然后你只能添加id_buyer = 1一次。

如果你真的不想失败:

select count(*) as num where id_buyer=1
#get num into your code
if(num==0) 
  insert

答案 2 :(得分:0)

第1步:  从db中选择记录,然后构造成数组, 第2步:  最后你可以从上面选择的记录中插入查询,

这应该很容易

答案 3 :(得分:0)

对不起伙计我是这个东西的新手,但实际上重点是我想确保所有新记录都插入到新表中,使用php有点难以导致循环导致速度减慢所以我确实触发了MySQL和结果与我想要的结果相同。

DELIMITER |

CREATE DEFINER = 'root'@'localhost' TRIGGER `copy_berkas`
AFTER INSERT
ON `buyer`
FOR EACH ROW
INSERT INTO kelengkapan_berkas 
(id_buyer, nama_berkas) 
SELECT NEW.id, jenis_berkas.nama_berkas 
FROM jenis_berkas WHERE jenis_berkas.id_job = NEW.job|

DELIMITER ;

对不起麻烦