MySQL:如何连接四个表(Active Record语法)

时间:2012-05-11 17:14:52

标签: mysql codeigniter join normalization

对于ID为20的材质表中的特定材料,我有两个表:

chemical_name_id | chemical_name  (table name: ml_chemical_names)
================================
1                | Polysomething

common_name_id | common_name (table name: ml_common_names)
=============================
1              | PMMA
2              | Lucite
3              | Perspex
4              | Plexiglas

material_id | material  (table name: ml_materials)
======================
20          | Acrylic

我加入这些表时有点绿,但我创建了两个查找表,如下所示:

material_id | common_name_id (table name: ml_materials_common_names)
============================
20           | 1
20           | 2
20           | 3
20           | 4

and

material_id | chemical_name (table name: ml_materials_chemical_names)
===========================
20          | 1

以下是我的Active Directory(CodeIgniter)格式的SQL:

$this->db->like('cn.common_name', $options['keyword']);
$this->db->or_like('chem.chemical_name', $options['keyword']);
$this->db->join('ml_materials_chemical_names mchem', 'mchem.material_id = m.material_id', 'inner');
$this->db->join('ml_chemical_names chem', 'chem.chemical_name_id = mchem.chemical_name_id', 'inner');
$this->db->join('ml_materials_common_names mcn', 'mcn.material_id = m.material_id', 'inner');
$this->db->join('ml_common_names cn', 'cn.common_name_id = mcn.common_name_id', 'inner');
return $this->db->get('ml_materials m')->result();

这用于AJAX搜索表单。事情是,当搜索“polysomething”时,我得到四个结果。我只想要一个。我不确定这是我的桌子是否被错误或我的加入。我尝试过左,右和外连接,并且在返回的结果方面似乎没有任何变化。

有人可以帮忙吗?

0 个答案:

没有答案