join通常有下面几种类型,不同类型的join操作会影响返回的数据结果。
- INNER JOIN: 等同于 JOIN(默认的JOIN类型),如果表中有至少一个匹配,则返回行
- LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行
- RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行
- FULL JOIN: 只要其中一个表中存在匹配,就返回行
说明
object
join
( mixed
join
[, mixed $condition =
null
[,
string
$type =
'INNER'
]] )
JOIN方法也是连贯操作方法之一,用于根据两个或多个表中的列之间的关系,从这些表中查询数据。
参数
join
要关联的(完整)表名以及别名
支持三种写法:
写法1:[
'完整表名或者子查询'=>'别名'
] 写法2:'完整表名 别名'
写法3:'不带数据表前缀的表名'
condition
关联条件。可以为字符串或数组, 为数组时每一个元素都是一个关联条件。
type
关联类型。可以为:INNER、LEFT、RIGHT、FULL,不区分大小写,默认为INNER。
返回值
模型对象
举例
Db::table
('think_artist')
->alias
('a')
->join
('think_work w','a.id = w.artist_id')
->join
('think_card c','a.card_id = c.id')
->select();
Db::table
('think_artist')
->alias
('a')
->join
('__WORK__ w','a.id = w.artist_id')
->join
('__CARD__ c','a.card_id = c.id')
->select();
$join = [ ['think_work w','a.id=w.artist_id'], ['think_card c','a.card_id=c.id'], ]; Db::table
('think_user')->alias
('a')->join
($join)->select();
以上三种写法的效果一样,__WORK__
和__CARD__
在最终解析的时候会转换为think_work
和think_card
。注意:'_表名_'这种方式中间的表名需要用大写
如果不想使用别名,后面的条件就要使用表全名,可以使用下面这种方式
Db::table
('think_user')->join
('__WORK__','__ARTIST__.id = __WORK__.artist_id')->select();
默认采用INNER JOIN 方式,如果需要用其他的JOIN方式,可以改成
Db::table
('think_user')->alias
('a')->join
('word w','a.id = w.artist_id','RIGHT')->select();
表名也可以是一个子查询
$subsql = Db::table
('think_work')->where
(['status'=>1])->field
('artist_id,count(id) count')->group
('artist_id')->buildSql(); Db::table
('think_user')->alias
('a')->join
([$subsql=>
'w'],
'a.artist_id = w.artist_id')->select();
因buildSql返回的语句带有(),所以这里不需要在两端再加上()。