ywj001 发表于 2012-10-18 10:33:32

求助:where和like,or_like组合使用产生的问题

我使用了where和多个like,or_like,代码段如下:

if ($level=='r'){$where="tb_hotel.region_id";}else{$where="tb_province.id";}
$query=$this->db
->select('tb_hotel.*,tb_region.region,tb_province.province')
->from('tb_hotel')
->where($where,$id)
->join('tb_region','tb_hotel.region_id = tb_region.id','inner')
->join('tb_province','tb_region.province_id = tb_province.id','inner')
->like('hotel_name',$key)
->or_like('contact',$key)
->order_by($sortField,$sortOrder)
->limit($size,$start)
->get();


生成的SQL语句是这样的

SELECT `tb_hotel`.*, `tb_region`.`region`, `tb_province`.`province`
FROM (`tb_hotel`)
INNER JOIN `tb_region` ON `tb_hotel`.`region_id` = `tb_region`.`id`
INNER JOIN `tb_province` ON `tb_region`.`province_id` = `tb_province`.`id`
WHERE `tb_hotel`.`region_id` = '1'
AND `hotel_name` LIKE '%%'
OR `address` LIKE '%%'
ORDER BY `id` asc LIMIT 10


这个SQL语句和我的初衷不同,产生的结果也不是想要的结果
我希望where中的条件是必经条件,
而生成的语句中,因为缺少(),导致只要OR `address` LIKE '%%'条件为true时,where条件被忽略。

我想要的SQL语句其实是

SELECT `tb_hotel`.*, `tb_region`.`region`, `tb_province`.`province`
FROM (`tb_hotel`)
INNER JOIN `tb_region` ON `tb_hotel`.`region_id` = `tb_region`.`id`
INNER JOIN `tb_province` ON `tb_region`.`province_id` = `tb_province`.`id`
WHERE `tb_hotel`.`region_id` = '1'
AND (`hotel_name` LIKE '%%'
OR `address` LIKE '%%')
ORDER BY `id` asc LIMIT 10


请高人告知该怎么解决?难道要自己动手组装SQL语句?


ywj001 发表于 2012-10-18 10:53:07

看来AR对付这个有困难,已手动组装where子句。已解决

Hex 发表于 2012-10-18 11:05:46

确实太复杂的 SQL 用 AR 不是太好。

bingdong700 发表于 2013-7-18 11:34:57

自定义字符串:
你可以手动的编写子句:

$where = "name='Joe' AND status='boss' OR status='active'";

$this->db->where($where);

纯屌丝 发表于 2013-12-10 14:47:07

我也遇到这个问题很多次了,真是够烦人
页: [1]
查看完整版本: 求助:where和like,or_like组合使用产生的问题