PHP将行插入数据库

时间:2012-12-27 19:12:40

标签: php mysql

我已经问过这个问题,但问题是在没有回答的情况下结束,所以我发布了新的问题。  我试图添加第二个表中缺少的值 在表ps_psroduct供应商中缺少一些值,我想从ps_product添加。所以我想列出缺少的值并将它们插入到ps_product_supplier中,没有重复。 ps_product中的某些值在ps_product_supplier中是相同的但不是全部,所以我想过滤thoese值并正确插入它们。 所以ps_product中存在一些值但ps_product_supplier中没有,我想通过检查id_product并添加缺失来在表中插入缺失的行。 我现在拥有的是我打印了所有值但我只需要缺少可以在ps_product_supplier中插入它们的值

怎么做? 在输出中我得到:

USPJESNO ID 1 ne postoji u drugoj tablici i trenutno: 0
USPJESNO ID 2 ne postoji u drugoj tablici i trenutno: 1
USPJESNO ID 3 ne postoji u drugoj tablici i trenutno: 2
USPJESNO ID 4 ne postoji u drugoj tablici i trenutno: 3
USPJESNO ID 5 ne postoji u drugoj tablici i trenutno: 4
USPJESNO ID 6 ne postoji u drugoj tablici i trenutno: 5

对于所有值,但我需要mach ID并且只打印缺失并在ps_product_supplier中为其创建一行,其值来自ps_product

$kveri = "SELECT id_product,id_supplier,supplier_reference, wholesale_price FROM ps_product";

    $ispis = mysql_query($kveri) or die(mysql_error());

               while ($row = mysql_fetch_array($ispis)){


               $trenutnired = $row['id_product'];
               $trenutnired1 = 0;
               $trenutnired2 = $row['id_supplier'];
               $trenutnired4 = $row['supplier_reference'];
               $trenutnired5 = $row['wholesale_price'];
               $trenutnired6 = 3;



                                                            //echo $trenutnired;

            //$drugatab = "SELECT * FROM ps_product_supplier WHERE id_product = '$trenutnired'";
            $drugatab = "SELECT id_product FROM ps_product_supplier WHERE id_product = '$trenutnired'";
            $rezultati = mysql_query($drugatab) or die(mysql_error());
                if(mysql_num_rows($rezultati)){
            // Successful query...

            echo "USPJESNO ID $trenutnired ne postoji u drugoj tablici i trenutno: $countUpdated<br />";
            //mysql_query("INSERT INTO ps_product_supplier (id_product_supplier, id_product, id_product_attribute, id_supplier, product_supplier_reference, product_supplier_price_te, id_currency)  VALUES ('', '$trenutnired', '$trenutnired1',  '$trenutnired2', '$trenutnired4', '$trenutnired5', '$trenutnired6')");
            $countUpdated++;
        } else {
            //$countUpdated++;
            echo "ID $trenutnired ne postoji u drugoj tablici i trenutno: $countUpdated<br />";
        }
        }

此查询适用于一个ID以插入数据,但我需要所有缺少的内容:

INSERT INTO ps_product_supplier 
(id_product_supplier, id_product, id_product_attribute, id_supplier,
product_supplier_reference, product_supplier_price_te, id_currency)  
VALUES(NULL, 6216, 0, (SELECT id_supplier FROM ps_product WHERE id_product = 6216),
(SELECT supplier_reference FROM ps_product WHERE id_product = 6216), 
(SELECT wholesale_price FROM ps_product WHERE id_product = 6216), 3);

1 个答案:

答案 0 :(得分:1)

我认为您正在尝试在ps_products中选择 的产品,但在ps_productsuppliers中。如果我是对的,这种方式可能是最容易理解的。

select id_product
from ps_products
where id_product not in (select id_product from ps_product_supplier;