我有两个表:
- 具有属性的客户表:CCD_ 1
- 具有属性的信用卡表:
id, firstName, lastName
目标是,只有当客户存在于信用卡表中时,我才需要将其插入客户表。所有信息都来自用户的输入。
这就是我尝试做的:
IF EXISTS
(SELECT first_name, last_name
FROM creditcards
WHERE creditcards.first_name = ?
AND creditcards.last_name = ?
)
BEGIN
INSERT INTO customers(first_name, last_name, address,email,password)VALUES (?,?,?,?,?)
END
我还为七个"?"做了setString。但它抱怨该语句中存在语法错误。
您不能在MySQL中的函数之外使用IF
控制块。这就是语法错误背后的原因。构造查询的一种方法是INSERT
中的SELECT
,类似于以下内容:
INSERT INTO customers (`first_name`,`last_name`,`address`,`email`,`password`)
SELECT first_name, last_name, address, email, password
FROM (SELECT ? as first_name, ? as last_name, ? as address, ? as email, ? as password) a
WHERE EXISTS (SELECT 1 FROM creditcards b WHERE a.first_name = b.first_name AND a.last_name=b.last_name);