简体   繁体   English

在将数据添加到 mysql 数据库中的表之前检查

[英]Check before adding the data into table in mysql database

I am trying to insert data in table emp_master where token_no and vehicle_no is available, I am using mentioned below query to add and check the record我正在尝试在表 emp_master 中插入数据,其中 token_no 和 vehicle_no 可用,我使用下面提到的查询来添加和检查记录

insert into emp_master (token_no, vehicle_no) values (1234,12345) where not exists (select * from emp_master where vehicle_no = '12345');

but whenever I am trying this then error comes in as但是每当我尝试这样做时,就会出现错误

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 not exists (select * from emp_master where vehicle_no = '12345')' at line 1

The suggestion will be helpful该建议会有所帮助

If you need to have this check in your insert statement, you can structure it like this:如果您需要在插入语句中进行此检查,您可以像这样构造它:

SQL Fiddle : http://sqlfiddle.com/#!9/d3dd77/1 SQL小提琴http : //sqlfiddle.com/#!9/d3dd77 /1

insert into emp_master (token_no, vehicle_no) 
select 1234, 12345
from dual
where not exists (select * from emp_master where vehicle_no = '12345');

Another way to do this on any DBMS:在任何 DBMS 上执行此操作的另一种方法:

DB Fiddle Demo 数据库小提琴演示

insert into emp_master (token_no, vehicle_no) 
select token_no, vehicle_no
from (
select 1234 token_no, 12345 vehicle_no
) rec
where not exists (select * from emp_master where vehicle_no = rec.vehicle_no);

Put a UNIQUE constraint on the vehicle_no column, and then insert the data with no WHERE clause.vehicle_no列上放置一个UNIQUE约束,然后插入没有WHERE子句的数据。 Instead, handle the exception if it fails.相反,如果它失败,则处理异常。

You can use an INSERT ... SELECT query to achieve this functionality:您可以使用INSERT ... SELECT查询来实现此功能:

INSERT INTO emp_master (token_no, vehicle_no) 
SELECT 1234, 12345
WHERE NOT EXISTS (SELECT * FROM emp_master WHERE vehicle_no = '12345')

Demo on dbfiddle dbfiddle 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM