(1)
$model = M();
$info = $model->table(‘vote_info‘)->alias(‘v‘)
->field(‘v.*, u.real_name, g.group_name‘)
->join(‘user_info as u on v.user_id = u.id‘)
->join(‘group_info as g on g.id = u.group_id‘)
->where($where)
->order(‘v.create_time desc‘)
->select();
或
$model = M();
$list = $model->table("message m")
->field("m.time,m.content,u.nickname as name,u.head_img as img")
->join("left join user_info as u on m.user_id=u.id")
->where($map)->select();
或
$model = M();
$list = $model->table("message m left join user_info u on m.user_id=u.id")
->field("m.time,m.content,u.nickname as name,u.head_img as img")
->where($map)->select();
(2)
$sql = "SELECT u.real_name, n.id, n.note_title, n.note_tags, n.create_time, t.type_name FROM notes_info AS n INNER JOIN user_info AS u ON n.user_id=u.id INNER JOIN note_type AS t ON n.sort_id=t.id WHERE n.status=0 AND n.user_id=".$where[‘user_id‘]." ORDER BY n.id DESC";
$res = $personal_list->query($sql);
select a.id,a.name,a.keyword,a.descripttion,b.l_id,b.listcoment,b.text from dome as a, list as b where a.id=b.id and a.id=1 order by a.sord ASC,order by id DESC;
我们也可以改写成LEFT JOIN ..ON语句
select a.id,a.name,a.keyword,a.description,b.l_id,b.listcoment,b.text from dome as a LEFT JOIN list as b ON a.id=b.id where a.id=1 order by a.sord ASC,order by id DESC;
总体来说第二条语句是比较实用,好处在查询数据表dome表的数据,不论数据表list中是否有dome中的数据那么都会查询的出来dome中的值
第一条查询语句与第二条语句不通之处是查询dome数据表与list数据表中的id为1时,如果dome中有数据而list中没有数据那么查询出来的结果为空,
也可以多关联查询语句与双关联查询方法类似
from dome as a LEFT JOIN list as b ON a.id=b.id,LEFT JOIN TABLE AS c ON a.id=c.id,LEFT JOIN TABLE as d ON a.id=d.id
group by语句
当语句中出现count或者max 或者其他的一些函数的时候就会用到group by语句
select a.*,count(b.id) from dome as a left join list as b ON a.id=b.id where a.id=1 GROUP BY a.id;