thinkphp构建子查询sql语句写法
从3.0版本开始新增了子查询支持,有两种使用方式:
1、使用select方法 当select方法的参数为false的时候,表示不进行查询只是返回构建SQL,例如:
// 首先构造子查询SQL
$subQuery = $model->field('id,name')->table('tablename')->group('field')->where($where)->order('status')->select(false);
当select方法传入false参数的时候,表示不执行当前查询,而只是生成查询SQL。
2、使用buildSql方法
$subQuery = $model->field('id,name')->table('tablename')->group('field')->where($where)->order('status')->buildSql();
调用buildSql方法后不会进行实际的查询操作,而只是生成该次查询的SQL语句(为了避免混淆,会在SQL两边加上括号),然后我们直接在后续的查询中直接调用。
// 利用子查询进行查询
$model->table($subQuery.' a')->where()->order()->select()
构造的子查询SQL可用于ThinkPHP的连贯操作方法,例如table where等。
例子:
$subQuery = M('Withdraw')
->alias('a')
->field('transaction_id,(select username from ' . C("DB_PREFIX") . 'user as b where a.user_id = b.user_id) as username,(select true_name from ' . C("DB_PREFIX") . 'user as b where a.user_id = b.user_id) as true_name,amount,withdraw_id,bank_name,bank_subbranch_name,card_number,apply_time,withdraw_status,withdraw_time,handle_mark')
->union('SELECT `transaction_id`,
(select username from '.C("DB_PREFIX").'shop as d left join '.C("DB_PREFIX").'user as b on d.principal_id=b.user_id where a.shop_id = d.shop_id) as username,
(select shop_name from '.C("DB_PREFIX").'shop as b where a.shop_id = b.shop_id) as true_name,
`amount`,`withdraw_id`,`bank_name`,`bank_subbranch_name`,`card_number`,`apply_time`,`withdraw_status`,`withdraw_time`,`handle_mark`
FROM 1dcq_shop_withdraw a')->buildSql();
$table = M()->field('transaction_id,username,true_name,amount,withdraw_id,bank_name,bank_subbranch_name,card_number,apply_time,withdraw_status,withdraw_time,handle_mark')
->table($subQuery.' n')
->where($where)
->order('apply_time desc')
->select();
echo M()->getLastSql();exit;
输出:SELECT `transaction_id`,`username`,`true_name`,`amount`,`withdraw_id`,`bank_name`,`bank_subbranch_name`,`card_number`,`apply_time`,`withdraw_status`,`withdraw_time`,`handle_mark` FROM ( SELECT `transaction_id`,(select username from 1dcq_user as b where a.user_id = b.user_id) as username,(select true_name from 1dcq_user as b where a.user_id = b.user_id) as true_name,`amount`,`withdraw_id`,`bank_name`,`bank_subbranch_name`,`card_number`,`apply_time`,`withdraw_status`,`withdraw_time`,`handle_mark` FROM 1dcq_withdraw a UNION SELECT `transaction_id`,(select username from 1dcq_shop as d left join 1dcq_user as b on d.principal_id=b.user_id where a.shop_id = d.shop_id) as username,(select shop_name from 1dcq_shop as b where a.shop_id = b.shop_id) as true_name,`amount`,`withdraw_id`,`bank_name`,`bank_subbranch_name`,`card_number`,`apply_time`,`withdraw_status`,`withdraw_time`,`handle_mark` FROM 1dcq_shop_withdraw a ) n WHERE `withdraw_status` NOT IN ('0','1','3') ORDER BY apply_time desc