MySQL ForEach Loop
This article describes how to simulate a foreach loop in MySQL using INSERT, SELECT, WHERE, and JOIN in one statement.
MySQL foreach loop
To understand foreach loop simulation, let us create three tables with the following names and attribute names.
Tables and their respective properties:
users -> id, user_name, person_id, email
person -> id, person_name, address_id
address -> id, email
We use the following statement to create the table.
# create `address`, `person`, and `users` tables
CREATE TABLE address(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(45) NULL
);
CREATE TABLE person (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
person_name VARCHAR(45) NOT NULL,
address_id INT NULL,
FOREIGN KEY (address_id) REFERENCES address(id)
);
CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(45) NOT NULL,
person_id INT NOT NULL,
email VARCHAR(45) NOT NULL,
FOREIGN KEY (person_id) REFERENCES person(id)
);
Also, use the following MySQL query to insert data into the table we just created.
# insert data into the `address` table. Here
# we have parenthesis only because one field
# is `auto_incremented`, and the other can accept
# `null`.
INSERT INTO address () VALUES (),(),(),();
# insert data into the `person` table
INSERT INTO person (person_name)
VALUES
('Thomas Christopher'),
('Jim James'),
('Mehvish Ashiq'),
('Saira Daniel');
# insert data into the `users` table
INSERT INTO users(user_name, person_id, email)
VALUES
('chthomas', 1, 'chthomas@yahoo.com'),
('jjames', 2, 'jimjames@gmail.com'),
('mehvishashiq', 3, 'mehvish@yahoo.com'),
('danielsaira', 4, 'sairad@gmail.com');
Next, we use a SELECT statement to view the most recent data.
# display data for all the specified tables
SELECT * FROM users;
SELECT * FROM person;
SELECT * FROM address;
Output (for the users table):
+----+--------------+-----------+--------------------+
| id | user_name | person_id | email |
+----+--------------+-----------+--------------------+
| 1 | chthomas | 1 | chthomas@yahoo.com |
| 2 | jjames | 2 | jimjames@gmail.com |
| 3 | mehvishashiq | 3 | mehvish@yahoo.com |
| 4 | danielsaira | 4 | sairad@gmail.com |
+----+--------------+-----------+--------------------+
4 rows in set (0.00 sec)
Output (for the person table):
+----+--------------------+------------+
| id | person_name | address_id |
+----+--------------------+------------+
| 1 | Thomas Christopher | NULL |
| 2 | Jim James | NULL |
| 3 | Mehvish Ashiq | NULL |
| 4 | Saira Daniel | NULL |
+----+--------------------+------------+
4 rows in set (0.00 sec)
Output (for the address table):
+----+-------+
| id | email |
+----+-------+
| 1 | NULL |
| 2 | NULL |
| 3 | NULL |
| 4 | NULL |
+----+-------+
4 rows in set (0.11 sec)
If users.person_id is not null and person.address_id is null, we should create a new record in the addresses table. The newly created row will have the exact same email as users.email.
Here, we can simulate the foreach loop in the following way.
# simulation of `foreach loop`
INSERT INTO address (email) SELECT users.email
FROM users JOIN person ON users.person_id = person.id
WHERE person.address_id IS NULL;
Next, use a SELECT query to view the updated data.
SELECT * FROM address;
Output:
+----+--------------------+
| id | email |
+----+--------------------+
| 1 | NULL |
| 2 | NULL |
| 3 | NULL |
| 4 | NULL |
| 5 | chthomas@yahoo.com |
| 6 | jimjames@gmail.com |
| 7 | mehvish@yahoo.com |
| 8 | sairad@gmail.com |
+----+--------------------+
8 rows in set (0.00 sec)
However, we can also use cursors and procedures to perform the above query.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Display tables and database structure in MySQL
Publish Date:2025/04/23 Views:97 Category:MySQL
-
Today, we will learn about queries in MySQL that can display the table and database structure. We will use the mysqldump utility, DESCRIBE the , SHOW TABLES and SHOW CREATE TABLE the statements. We are using MySQL version 8.0.28 while writi
Select first row from MySQL table
Publish Date:2025/04/23 Views:112 Category:MySQL
-
Today, we will explore three scenarios and their solutions where we want to select the first row from a MySQL table. In the first scenario, we will learn to get the first row from a MySQL table where there are multiple instances of a partic
Insert timestamp into MySQL table
Publish Date:2025/04/23 Views:77 Category:MySQL
-
Today, we will learn how to TIMESTAMP insert date and time into a type column of a MySQL table according to the table definition. Create a MySQL table First, we will create the tables that we will use in this tutorial. Sample code: CREATE T
The difference between two tables in MySQL
Publish Date:2025/04/23 Views:102 Category:MySQL
-
In this article, we will learn how to find the difference between two tables in MySQL. The difference between two tables in MySQL We often need to compare two tables to find records in one table that have no matching records in the other ta
MySQL sorts data alphabetically
Publish Date:2025/04/23 Views:129 Category:MySQL
-
In this article, we will learn about various ways to sort data alphabetically in MySQL. Sort MySQL data alphabetically When you use the SELECT command to query data from a table, the rows in the result set are in arbitrary order. To order t
Display the current database in MySQL
Publish Date:2025/04/23 Views:199 Category:MySQL
-
This article focuses on the various queries that can be used to display the current database in MySQL. We will learn by using the Windows command line and MySQL Workbench. Display the current database in MySQL We can use the following query
Check if a database exists in MySQL
Publish Date:2025/04/23 Views:179 Category:MySQL
-
In this article, we will introduce many ways to check if a database exists in MySQL. Check if the database exists in MySQL The system schema is the schema that MySQL uses. It includes tables that contain data needed by a running MySQL serve
Get the sum of multiple columns in MySQL
Publish Date:2025/04/23 Views:125 Category:MySQL
-
In this article, we will learn how to sum multiple columns in MySQL. Sum multiple columns in MySQL You can use aggregate functions SUM() to calculate the total value in a collection. SUM() The function calculation does not consider NULL val
Converting from datetime type to date-only in MySQL
Publish Date:2025/04/23 Views:199 Category:MySQL
-
Today, we will learn the DATE(), CAST(), CONVERT() and DATE_FORMAT() methods to convert DATETIME type to DATE type in MySQL. The above mentioned methods can be used in MySQL 4.0 and above. Converting from DATETIME to DATE in MySQL To unders