case when 多条件查询

在为客户创建列表时,遇到一个需求:根据广告类型从不同的表中检索数据。例如,当itemType为1时,从information表中选取del_flag为0的ID和title;为2时,从goods表获取相同条件的数据;为3时,从store表中选取audit_Type为1的ID和name。解决方案是使用MySQL的case when语句进行多条件查询,成功实现了根据itemType值从不同表获取item_id。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给客户做列表新增的时候,有个需求:根据广告类型从不同的表查询数据,保存到数据库。代码如下所示:

<div class="form-group" id="adType">
    <label>类型:</label>
    <select id='itemType' name="itemType">
        <option value="">请选择</option>
        <option value="1">资讯</option>
        <option value="2">商品</option>
        <option value="3">店铺</option>
        <option value="4">网页</option>
    </select>
</div>

资讯 (带搜索的下拉框) 1
Information 从information表中取ID和title del_flag为0的

/pet/web/information/information-web!getInfoSelectData

商品(搜索的下拉框) 2
goods 从goods表中取ID和name del_flag为0的

/pet/web/goods/goods-web!getGoodsSelectData

店铺(搜索的下拉框) 3
store 从store表中取ID和name audit_Type为1的(已审核)

/pet/web/store/store-web!getStoreSelectData

网页(输入链接地址)4 手动输入

综上所述,需要根据itemType的值从不同的数据库获取item_id的值。
下面是查询的语句,通过case when在MySQL中查询

(case 
  when (item_type = '1') then 
  (select  i.title from information i where i.id = item_id) 
  when (item_type = '2') then
  (select  g.name from goods g where g.id = item_id) 
  when (item_type = '3') then
  (select s.name from store s where s.id = item_id) 
  WHEN (item_type = '4') THEN 
  item_id 
  end
  ) as goodsName,

大功告成!第一次使用case when。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值