Mysql determines whether to insert data based on the conditions, and mysql inserts data based on the conditions.

Source: Internet
Author: User

Mysql determines whether to insert data based on the conditions, and mysql inserts data based on the conditions.

This problem is actually divided into two aspects:

1. Determine whether to insert data based on the table's primary key.

2. Determine whether to insert a table based on its non-primary key.

Suppose there are tables DOC_INFO (Doctor table), combined primary key HOS_ID (hospital code), DEPT_CODE (Department Code), DOC_NO (Doctor code), non-primary key field DOC_NAME Doctor name, etc.

If you determine whether to insert data based on HOS_ID and DOC_NAME, write it as (DULE is a temporary table and does not need to be defined)

Insert into doc_info SELECT 35,12, '20140901', 'cheonan ', 1, '', null,'', '2017-09-21 00:00:00 ', null, '','', null, null

From dual where not exists (SELECT 1 FROM doc_info where hos_id = 35 and doc_name = 'cheonan ')

If you determine whether to insert data based on HOS_ID, DEPT_CODE, and DOC_NO, write

Insert into doc_info VALUES
(3850, '20140901', 'gennan ', 1, '', null,'', '2017-09-21 00:00:00 ',
Null, '','', null, null)
On duplicate key update add_time = '2017-09-21 00:00:00'

 

Differences:

1. Determine whether to insert data based on non-primary keys. It is mainly used to insert data that is not inserted according to the document specification and to temporarily remedy some missing data.

2. Determine whether to insert a primary key to update the latest status of some fields in the table. This is used when fields need to be updated frequently.

Thanks for the technical support:

Https://my.oschina.net/jsan/blog/270161/

Http://www.jb51.net/article/39255.htm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.