INSERT INTO Users( weight, desiredWeight )
select val1 , val2 from tableXShoulatNotBeUsers
WHERE somecondition;
(b) IF 记录已经存在使用更新代替插入:
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
应该是
Update Users set weight=160, desiredWeight=145 WHERE id = 1;
C)。如果要同时更新或插入
Replace Users set weight=160, desiredWeight=145 WHERE id = 1;
Note):- you should provide values to all fields else missed field in query
will be set to null
如果你想从同一个表中克隆一条记录,只要记住你不能选择
从表中插入,因此
create temporary table xtable ( weight int(11), desiredWeight int(11) ;
insert into xtable (weight, desiredWeight)
select weight, desiredWeight from Users where [condition]
insert into Users (weight, desiredWeight)
select weight , desiredWeight from xtable;
SELECT count(*)
FROM customers
WHERE city = 'Newark';
可以通过使用 EXISTS 条件确保不插入重复信息。
例如,如果有一个名为 client 的表,其主键为 client _ id,则可以使用以下语句:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
此语句使用子选择插入多条记录。
如果要插入单条记录,可以使用以下语句:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
在 INSERT INTO... VALUES... 之后添加 WHERE 子句只是无效的 SQL,不会解析。
MySQL 返回的错误是:
mysql> INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 1' at line 1
INSERT INTO Users(weight, desiredWeight )
select '$userWeight', '$userDesiredWeight'
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
INSERT INTO Users(weight, desiredWeight )
SELECT '$userWeight', '$userDesiredWeight'
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
INSERT INTO tablename(fullname,email)
SELECT * FROM (SELECT 'fullnameValue' AS fullname_field,'emailValue' AS email_field) entry WHERE entry.email_field NOT IN (SELECT email FROM tablename);