I have a contacts table and a codes table. A contact has many codes:
mysql> DESCRIBE contacts;
+------------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| first_name | varchar(255) | YES | | NULL | |
| last_name | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL |
mysql> DESCRIBE codes;
+-----------------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| code | varchar(255) | YES | | NULL | |
| contact_id | int(11) | YES | | NULL | |
I can retrieve all contacts who have codes:
SELECT * FROM `contacts`
INNER JOIN `classification_codes`
ON `contacts`.`id` = `codes`.`contact_id`;
Unfortunately, this will return only unique contact records even if the contact has many codes. If, for example, the contact has two codes, I want to retrieve the same contact record twice, with each record associated separately with each code. How can I accomplish this in mysql?
Change order of tables to get all codes that has contacts. That should do the trick
Just change tables order:
SELECT * FROM `classification_codes`
INNER JOIN `contacts`
ON `contacts`.`id` = `codes`.`contact_id`;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.