How do I do select from a one-to-many relationship

2019-06-13 15:32发布

问题:

I have a number of tables that I'm trying to access in CodeIgniter, and one of them is basically a collection of foreign keys from the other tables, most of which are only two fields: a unique id and a name. The "campaigns" table, let's call it, pulls data from other tables in the form of those tables' ids (because the names may not be unique).

Now what I want to do is display the "campaigns" data in human-readable form, meaning, showing the foreign names, not the ids. I think this is called a 'join,' but I'm not 100% certain on that. I checked MySql's page and they say that that isn't actually what foreign keys are for, but I thought that you needed foreign keys for a join, so I'm really just more confused now.

Do I really use joins and foreign keys for this? Thanks in advance.

回答1:

The foreign key provides a link to another record in the same or another table (usually the latter). A join uses common data in two tables (sometimes the same table) to provide a link between them.

If you have two tables that you want to join and the only common factor between those two tables is in a third table (the one with all the foreign keys) you will need to perform 2 joins.

Example

SELECT *.table1, *.table2 FROM table1
LEFT JOIN foreign_key_table ON foreign_key_table.id1 = table1.id
LEFT JOIN table2 ON foreign_key_table.id2 = table2.id
WHERE.....

In Codeignter:

$this->db->select('*.table1, *.table2');
$this->db->from('table1');
$this->db->join('foreign_key_table', 'foreign_key_table.id1 = table1.id');
$this->db->join('table2', 'foreign_key_table.id2 = table2.id');
$this->db->where('...');

You can find all the information you need here - http://codeigniter.com/user_guide/database/active_record.html

Hope this helps.