yii2 sql操作姿势

union all

查询A用户过期优惠券的信息,过期的判断方式 status= 'invalid'
end_time<=当前日期

SELECT 
       `uc`.*
  FROM((
SELECT *
  FROM `user_coupon_list`
 WHERE(`user_id`= '4876936')  AND(`status`= 'invalid'))  UNION ALL(
SELECT *
  FROM `user_coupon_list`
 WHERE(`user_id`= '4876936')  AND(`end_time`<= '2021-05-14')  AND(`status`!= 'used')))  

对应代码

$query1 = UserCouponModel::find()->andWhere(['user_id' => $userId]);
$query2 = (clone $query1)->andWhere(['<=', 'end_time', date('Y-m-d')])
       ->andWhere(['!=', 'status', 'used']);
$result = $query1
          ->andWhere(['status' => 'invalid'])
          ->union($query2, true)
          ->all();

left join 连接子查询

brand_name模糊匹配品牌名,查询品牌信息和最低的商品价格
商品的筛选条件:goods_type= 1goods_type= 2 andimage_url!= ''

 SELECT `g`.`brand_id`,
       `b`.`id` AS `id`,
       `price`,
       `brand_name`,
       `logo`,
       `goods_type`
  FROM(
SELECT *
  FROM `brand_list`
 WHERE `brand_name` LIKE '%爱奇艺%')  `b`
  LEFT JOIN(
SELECT `id`, `brand_id`, min(price)  AS `price`
  FROM `goods`
 WHERE(`is_show`= 1)  AND((goods_type= 1)  OR(goods_type= 2
   and `image_url`!= ''))  GROUP BY `brand_id`)  `g` ON g.brand_id= b.id
 WHERE g.id is not null

对应代码

$goodsQuery = GoodsModel::find()
            ->select('id,brand_id,min(price) as price')
            ->where(['is_show' => 1])
            ->andWhere(['or', 'goods_type=1', 'goods_type=2 and `image_url`!= \'\''])
            ->groupBy('brand_id');


$result = BrandModel::find()
            ->from(['b' =>BrandModel::find()->where(['like', 'brand_name', $name])])
            ->select('g.brand_id,b.id as id,price,brand_name,logo,goods_type')
            ->leftJoin(['g' => $goodsQuery], 'g.brand_id=b.id')
            ->where('g.id is not null')
            ->asArray()
            ->all();

updateall() 更新多个数据行

GoodsOrderModel::updateAll(['status' => 4], [
                    'and',
                    [
                        'user_id' => $orderInfo['user_id'],
                        'status' => 1
                    ],
                    ['>', 'gold_member_amount', 0]
                ]);
MessageListModel::updateAll(
                [
                    'status' => 1,
                    'read_time' => date('Y-m-d H:i:s')
                ],
                "user_id = :user_id and id $op :id and status=0 and type=:type",
                [
                    ':user_id' => $this->user['user_id'],
                    ':id' => $this->params['msgId'],
                    ':type' => $msg['type']
                ]
            );
Coupon::updateAll(
                ['status' => CashCouponActivityUserCoupon::STATUS_INVALID],
                [
                    'and',
                    [
                        'activity_id' => $params['activity_id'],
                        'user_id' => (int)$params['user_id']
                    ],
                    ['between', 'created_time', $params['start_time'], $params['end_time']]
                ]

你可能感兴趣的:(yii2 sql操作姿势)