联表查询
用户表 tb_user interestid 对应 tb_interest中的id
tb_type 表 是一个大类
tb_interest 兴趣表 typeid 对应tb_type 表的id。然后问题是用一个sql语句查询出所有用户的兴趣所属的类别。
Db::query("select u.username, t.name from tb_user u join tb_interest i on u.interestid=i.id join tb_type t on t.id=i.typeid");
分组查询
查询出两门及两门以上不及格同学的各课的平均分。
select avg(score) from tb_score where name = (select name from tb_score where score < 60 GROUP BY name having count(name) >= 2 )。
having字句可以让我们筛选成组后的各种数据,where字句在聚合前先筛选记录,也就是说作用在group by和having字句前。而 having子句在聚合后对组记录进行筛选
group by语句中select指定的字段必须是“分组依据字段”,其他字段若想出现在select中则必须包含在聚合函数中,常见的聚合函数
issue 为彩票期数 lottery_id为彩票种类。查出 每种彩票的最新期数。
$data=$model->where("sales_status",1)->where("start_sales_time","<",$time)
->where("stop_sales_time",">",$time)->group("lottery_id")
->field('lottery_id,max(issue)')
->select();