You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

当location_id以拼接形式存储时,如何用WHERE条件筛选对应科室?

嘿,我明白你的问题了——你的location_id是用逗号拼接成字符串存储的,现在想用location id 3筛选出cardiology和hair这两个科室,但原来的where_in方法不管用对吧?这就给你几个可行的解决办法:

解决拼接存储的location_id筛选问题

方案一:用MySQL的FIND_IN_SET函数直接处理

这是最快速适配现有结构的办法,MySQL自带的FIND_IN_SET函数专门用来处理逗号分隔的字符串,能帮你检查目标id是否存在于拼接的字段值里。你只需要修改model代码:

public function get_location_departments($d) {
    // 先对参数做转义,避免SQL注入风险
    $escaped_id = $this->db->escape($d);
    // 使用FIND_IN_SET判断目标id是否在location_id的拼接字符串中
    $this->db->where("FIND_IN_SET($escaped_id, location_id)");
    $query = $this->db->get('department')->result();
    return $query;
}

方案二:重构数据库结构(长期推荐)

虽然FIND_IN_SET能解决当下问题,但从数据库设计的规范来看,用拼接字符串存储多对多关系是反范式的,会导致查询效率低、后续维护麻烦。更合理的做法是新建一张中间表(比如location_department),结构如下:

  • location_id(int类型,关联location表的id)
  • department_id(int类型,关联department表的id)

把原来拼接的location_id拆成中间表的多条记录:比如某科室原来的location_id是1,3,就插入两条记录(1, 该科室id)、(3, 该科室id)。

之后查询的model代码改成关联查询即可:

public function get_location_departments($d) {
    $this->db->select('department.*');
    $this->db->from('department');
    $this->db->join('location_department', 'department.id = location_department.department_id');
    $this->db->where('location_department.location_id', $d);
    $query = $this->db->get()->result();
    return $query;
}

这种方式不仅查询效率更高,后续扩展功能(比如统计某个地点的科室数量)也会更方便。

小提醒:优化Controller的参数获取

你现在直接用$_POST['location']有点不安全,CI框架里推荐用自带的输入类来获取参数,它会自动做安全处理:

public function get_location_departments() {
    $d = $this->input->post('location');
    $data['departments'] = $this->Hospital_model->get_location_departments($d);
    $this->load->view('frontend/ajax_get_departments',$data);
}

内容的提问来源于stack exchange,提问作者user_777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:22:41