指引网

当前位置: 主页 > 编程开发 > PHP >

CI框架join多表联合查询的例子

来源:网络 作者:佚名 点击: 时间:2017-05-24 21:25
[摘要]  join在mysql中就是多表联合查询了这个如果用在框架中是不是一样的呢,有什么区别呢,今天我们就一起来看看CI框架join多表联合查询的例子吧,具体如下。

mysql中join用法

内连接

1.概念:内联接是用比较运算符比较要联接列的值的联接

2.内连接:join 或 inner join

3.sql语句

select * from table1 join table2 on table1.id=table2.id

-------------结果-------------

idnameidscore

------------------------------

1lee190

2zhang2100

------------------------------

注释:只返回符合条件的table1和table2的列

 4.等价(与下列执行效果相同)

A:select a.*,b.* from table1 a,table2 b where a.id=b.id

B:select * from table1 cross join table2 where table1.id=table2.id (注:cross join后加条件只能用where,不能用on)

ci中join用法

那么在ci中又会有什么区别呢

例:用 A表中的每个ID 去查询这个 ID 在 people 表中的信息

$this->db->from('A');
$this->db->join('B', 'sites.id = B.id');

用 A表中的每个ID 去查询这个 ID 在 B表中的信息。 注意SQL的约定,如果一个列名在二张表中是重复的,你需要在列名前加上表名和一个"."号。因此sites.id在位置桌子中意谓id所在的表是sites。在进行SQL多表查询时,最好把列名进行唯一性的标识,这样可以避免产生岐义,也可以让你自己明了。

如:你执行以下语句

$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();

相当于 执行这条sql语句

SELECT * FROM blogs JOIN comments ON comments.id = blogs.id

如果你想要在查询中使用多个连接,可以多次调用本函数。

如果你需要指定 JOIN 的类型,你可以通过本函数的第三个参数来指定。可选项包括:left, right, outer, inner, left outer, 以及 right outer.

$this->db->join('comments', 'comments.id = blogs.id', 'left');

// 生成: LEFT JOIN comments ON comments.id = blogs.id

------分隔线----------------------------