簡體   English   中英

如果值存在於表1中,則插入表2中的mysql

[英]If value exists in table 1 insert into table 2 mysql

對於我的訂購系統,當管理員插入訂單時,我需要檢查他為訂單插入的客戶是否存在於我的客戶表中。
我正在嘗試類似的方法,但是沒有運氣。

$sql = "IF EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')
THEN insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";

錯誤:第一行語法錯誤。 怎么了
這是正確的方法嗎? 有沒有更好的辦法?

您可能想“向后”進行操作-如果存在則插入:

$sql = "insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
select '$customer', '$product', '$quantity', now(), '$note', '$employee'
from dual
where EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')";

這是您可以做的一個巧妙技巧:

$sql = "INSERT INTO `order`
    (`customer_id`, `product`, `quantity`,
                                `creation_time`, `order_note`, `order_employee`)
    SELECT `customer_id`, '$product', '$quantity', now(), '$note', '$employee'
        FROM `customer` WHERE `customer_id`='$customer'";

請注意,我相信您已經正確清理了變量!

但這只會在具有該ID的客戶存在的情況下插入訂單。

我認為您應該以另一種方式考慮您的問題。

繼續進行以下步驟:

1-我需要知道客戶我的客戶是否存在嗎?

$sql = "SELECT ID FROM customer WHERE customer_id = '$customer'";

2-我嘗試我的客戶,他存在嗎?

    If(!empty($result_cust)){
$sql = insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
}

這樣,您的代碼將更容易理解。

分而治之

他們說。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM