1,left join 表里有多条记录,只取一条记录的方法。
如下代码段所示,依据uid判断重复的记录,group by ,只显示一条记录。
若是group by查询较慢,也可这样写,在group by之前增加一个where条件,速度马上就上来。
select a.id from app a
left join (select uid,id,name from weixin where 索引条件 group by uid) b on a.id=b.uid
2,mysql根据表的一个字段决定去关联(join)那张表格
根据a表的type字段决定关联那张表
比如a, b, c 三张表.
实现的语句如下
SELECT a.id, a.type, a.touid, b.question as b_question, c.content as c_content FROM ls_message a
LEFT JOIN ls_question_for_one b
on a.content = b.id and a.type = 2
LEFT JOIN ls_reward c
on a.content = c.id and a.type = 3
where a.uid = 10
ORDER BY time
其中on 中a.type是关键, 这个查出来的结果每一行中只会b_question字段或者c_content字段一个有值.
php的Tp框架中join多个查询条件的写法
join('b.question b', 'a.content = b.id and a.type = 2', 'left')