thinkphp5.0 mysql 操作

left join on

在left join下,两者的区别:

  • on是在生成临时表的时候使用的条件,不管on的条件是否起到作用,都会返回左表 (table_name1) 的行。
  • where则是在生成临时表之后使用的条件,此时已经不管是否使用了left join了,只要条件不为真的行,全部过滤掉。

首先明确两个概念:

  • LEFT JOIN 关键字会从左表 (table_name1) 那里返回所有的行,即使在右表 (table_name2) 中没有匹配的行。
  • 数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
  • join()
    $Model->join(' work ON artist.id = work.artist_id')->join('card ON artist.card_id = card.id')->select();
    $Model->join('RIGHT JOIN work ON artist.id = work.artist_id')->select();
    $Model->join(array(' work ON artist.id = work.artist_id','card ON artist.card_id = card.id'))->select();
    默认采用LEFT JOIN 方式,如果需要用其他的JOIN方式,可以改成第二种
  • 如果join方法的参数用数组的话,只能使用一次join方法,并且不能和字符串方式混合使用。
     
  • Case具有两种格式。简单Case函数和Case搜索函数。 

    --简单Case函数
  • CASE sex 
             WHEN '1' THEN '男' 
             WHEN '2' THEN '女' 
    ELSE '其他' END 
    --Case搜索函数 
    CASE WHEN sex = '1' THEN '男' 
             WHEN sex = '2' THEN '女' 
    ELSE '其他' END 

    这两种方式,可以实现相同的功能。简单Case函数的写法相对比较简洁,但是和Case搜索函数相比,功能方面会有些限制,比如写判断式
  • M('game')->field('rate,times,CASE WHEN times>0 && times<50 THEN 1 WHEN times>=50 && times<100 THEN 2 WHEN times>=100 && times<500 THEN 3 WHEN times>=500 && times<1000 THEN 4 ELSE 5 END AS flag')->order('flag,rate DESC')->select();
  • SUM()函数用于计算一组值或表达式的总和
  • $pay_fee = M('order')->where(['deliverid' => $deliver_id, 'state' => ['IN', '4,5,10,12']])->sum('actualmoney');
    计算在指定状态下的实际支付运费的总金额

 

一、查询

查询某个字段在哪个数据库哪个数据表

select table_schema,table_name from information_schema.columns where column_name = '字段名';

table_schema(数据库名)    table_name(数据表)

 

find() 查询一个一维数组数据

/ table方法必须指定完整的数据表名
Db::table('think_user')->where('id',1)->find();
//find 方法查询结果不存在,返回 null,存在则返回一条一维数组

//多个字段相同条件的and查询优化,用'&'符号链接多个字段
Db::table('think_user')
    ->where('name&title','like','%thinkphp')
    ->find();
//多个字段相同条件的or查询优化,用'|'符号链接多个字段
Db::table('think_user')
    ->where('name|title','like','%thinkphp')
    ->find();
// 使用whereOr 方法进行OR关系查询,一般whereOr 方法根where 方法在一起使用
Db::table('think_user')
    ->where('id','>','10')
    ->whereOr('title','like','%thinkphp')
    ->find();
find()
$model = M('WxuserCollection');
$res1 = $model - >find(1);
$res2 = $model - >find(2);
$res3 = $model - >where('good_id=1105 AND store_id = 1 AND user_id = 20') - >find();
 
find获取一条数据,find(1)获取id为1的数据,find(2)获取id为2的数据。最后一个是获取条件为where的中的第一条数据。

 

select() 查询多维数组数据集

 

Db::table('think_user')->where('status',1)->select();
select 方法查询结果不存在,返回空数组,存在则返回二维数组集合

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值