mysql 链表查询的基本使用

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')
posted @   Lafite-1820  阅读(218)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示