Batch Select
SELECT *
FROM students
WHERE student_name IN ('Xinyang', 'Ruihan', 'Caomei');- This query retrieves all records from the
studentstable where thestudent_namematches one of the specified values:'Xinyang','Ruihan', or'Caomei'in one execution
Code
The
INoperator allows for filtering multiple values in a single query, making it efficient for batch selection.
Java Mybatis code example
The above method selects a batch of label values from the
metric_label_lookupindex table where the label values match the given error codes.
Batch Insert
INSERT INTO students (name, gender, height)
VALUES
('Xinyang', 'Male', 170),
('Ruihan', 'Female', 165),
('Caomei', 'Male', 170);- This query inserts multiple records into the
studentstable in a single execution
Code
The
VALUESclause specifies the data for each new record, including thename,gender, andheightcolumns. Batch insertion like this reduces the overhead compared to inserting each record individually.
Java Mybatis code example
Inserts a batch of error codes into the metric_label_lookup table.
Batch Update
UPDATE students
SET
height = CASE
WHEN name = 'Xinyang' THEN 175
WHEN name = 'Ruihan' THEN 165
END,
gender = 'male'
WHERE name IN ('Xinyang', 'Ruihan');
- This query updates multiple records and columns in the
studentstable in a single execution. This approach minimizes the need for multiple update queries by combining them into a single query
Code
The
CASEstatement dynamically assigns different values to theheightcolumn based on thenameof the student.The
gendercolumn is set to'Male'for all matching records.The
WHEREclause ensures that only rows where thenameis'Xinyang'or'Ruihan'are updated.
Java Mybatis code example
Updates the columns in the metric_label_lookup table for the given list of error codes.
Batch Upsert
INSERT INTO students (name, gender, height)
VALUES
('Xinyang', 'Male', 170),
('Ruihan', 'Female', 165),
('Caomei', 'Male', 170);
ON DUPLICATE KEY UPDATE
name = VALUES(name),
gender = VALUES(gender);- Batch upsert, which combines the operations of Batch Insert and Batch Update
Code
If a record with the same unique or primary key already exists, the
ON DUPLICATE KEY UPDATEclause updates the existing record with new values.If no matching record exists, a new row is inserted.
The
VALUES()function retrieves the values from theINSERTstatement for updating existing records.
Important
In MySQL, to use a non-primary column (like
name) to check for record existence, you must define a unique constraint on that column in the table schema.
