三个表使用CI加入

时间:2014-07-24 06:25:48

标签: php mysql codeigniter

我有三张桌子,我必须加入。我不是一个好的SQL编写者。可以请sombody帮我准备这个使用连接,

分支

branch_id | branch_name | branch_address
1           name1           address1

branch_services

bs_id | branch_id | service_id
1       1           1
2       1           2
3       1           4

服务

service_id | service_name
1               service1
2               service2
3               service3
4               service4

我需要从与每个分支相关的分支表和service_names中选择*,如此

结果

1 | name1 | address1 | service1 service2 service4 |

当我正在搜索时发现了一些叫group_concat的东西。它有效。但是如何将它与CI ???一起使用

4 个答案:

答案 0 :(得分:1)

$this->db->select('*');
$this->db->from('branches');
$this->db->join('branch_services','branches.branch_id = branch_services.branch_id', 'left');
$this->db->join('services','branch_services.service_id = services.service_id', 'left');
$query = $this->db->get();
if($query->num_rows() != 0)
       return $query->result_array();
else
       return false;

根据您的需要使用左,右,内等连接

答案 1 :(得分:0)

我没有测试但是试试这个

SELECT branches.*, services.service_name FROM branches LEFT JOIN branch_services ON branches.branch_id = branch_services.branch_id LEFT JOIN services ON services.service_id = branch_services.service_id 

答案 2 :(得分:0)

请尝试以下代码:

$this->db->select("branches.branch_name, branches.branch_address, services.service_name");
$this->db->from("branches");
$this->db->join("branch_services", "branches.id = branch_services.branch_id", "inner");
$this->db->join("services", "branch_services.service_id = services.id", "inner");
$query = $this->db->get();

$result = array();
if($query->num_rows() > 0)
{
    $result = $query->result_array();
}

echo "<pre>"; print_r($result);


这将打印在结果下方(如预期的那样):

Array
(
    [0] => Array
        (
            [branch_name] => name1
            [branch_address] => address1
            [service_name] => service1
        )

    [1] => Array
        (
            [branch_name] => name1
            [branch_address] => address1
            [service_name] => service2
        )

    [2] => Array
        (
            [branch_name] => name1
            [branch_address] => address1
            [service_name] => service4
        )

)

答案 3 :(得分:0)

我正在回答我自己的问题,以便有人发现它有用,

$this->db->select("branches.branch_name, branches.branch_address, group_concat(services.service_name)");
$this->db->from("branches");
$this->db->join("branch_services", "branches.id = branch_services.branch_id", "left");
$this->db->join("services", "branch_services.service_id = services.id", "left");
$query = $this->db->get();

group_concat是奇迹点