thinkphp5常用数据库查询组合

风信子 2021-06-26 16:22:19 275℃

1.多条件and查询

//*生成Sql语句:SELECT * FROM `user` WHERE ( `name` = '张三'  AND `age` = 18 )  
db('user')->where('name', '张三')->where('age', 18)->select();

2.and和or组合查询

//* SELECT * FROM `user` WHERE  `name` = '张三'  AND (  `age` = 18 OR `money` >= 1000 )
db('user')->where('name', '张三')->where(function ($query){
    $query->where('age', 18)->whereOr('money', '>=', '1000');
})->select();

3.or和and组合查询

//* SELECT * FROM `user` WHERE  `name` = '张三' OR (  `age` = 18  AND `money` >= 1000 )
db('user')->where('name', '张三')->whereOr(function ($query){
    $query->where('age', 18)->where('money', '>=', '1000');
})->select();

4.匿名函数子查询

//* SELECT * FROM `user` WHERE  `age` > ( SELECT AVG(age) FROM `user` )
db('user')->where('age', '>', function ($query){
    $query->table('user')->field('AVG(age)');
})->select();

5.多字段like查询

//*  SELECT * FROM `article` WHERE  ( `title` LIKE '%php%' OR `content` LIKE '%php%' )
db('article')->where('title|content', 'like', '%php%')->select();
标签: PHP, ThinkPHP, MySQL

非特殊说明,本博所有文章均为博主原创。