简体   繁体   English

mysql在一个有多种关系的情况下检索相同的记录

[英]mysql retrieving the same record in a has many relationship

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? 我怎样才能在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`;

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

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