多表联合
join() 多表联合查询
使用 join() 函数可以完成多表联合查询,参数:联合语句;
join() 语法
Code sqlLine:1复制1.
as
主表表1
别名left
|right
|inner
join
表2
as
表2
别名on
表1
.字段 = 表1
.字段left
|right
|inner
join
表3
as
表3
别名on
表2
.字段 = 表3
.字段
查询示例
Code phpLine:18复制1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.
- <?php
class
indexControllerextends
grace{public
function
index(){$db
= \db('students'
);//手动查询总数,比如:利用第一url参数记录总数
if
(empty
($_GET
['total'
])){$_GET
['total'
] =$db
->count
();- }
else
{echo
'使用 url 参数...'
;- }
$this
->students =$db
- ->join(
'as a left join '
.sc('db'
,'pre'
).'classes as b on a.st_classid = b.class_id'
)- ->page(
2
,$_GET
['total'
])- ->order(
'st_id desc'
)- ->fetchAll(
'a.*, b.*'
);- p(
$this
->students);- }
- }
说明
join 函数起始于 select 字段 from 主表名称 , 从此处开始编写联合查询语句;
连接方式区别
inner join(内连接)、left join(左连接)、right join(右连接) ,它们之间其实并没有太大区别,仅仅是查询出来的结果有所不同。
1.inner join(内连接),在两张表进行连接查询时,只保留两张表中完全匹配的结果集。
2.left join,在两张表进行连接查询时,会返回左表所有的行,即使在右表中没有匹配的记录。
3.right join,在两张表进行连接查询时,会返回右表所有的行,即使在左表中没有匹配的记录。
具体演示参考 https://www.cnblogs.com/lijingran/p/9001302.html