我正在尝试使用 codeingniter 的事件记录创建一个 SQL
语句,类似于:
SELECT *
FROM (`posts`)
JOIN `Post_images` ON `Post_images`.`post_id` = `posts`.`id`
WHERE `title` LIKE '% $SEARCHTERM %'
OR `content` LIKE '% $SEARCHTERM %'
AND `location` = ' $LOCATION '
GROUP BY `posts`.`id`
我的 PHP 目前是:
$this->db->like('title', $term);
$this->db->or_like('content', $term);
$this->db->group_by('posts.id');
$this->db->join('Post_images', 'Post_images.post_id = posts.id');
$query = $this->db->get_where('posts', array('location' => $location));
return $query->result_array();
该 PHP 生成的查询是:
SELECT *
FROM (`posts`)
JOIN `Post_images` ON `Post_images`.`post_id` = `posts`.`id`
WHERE `location` = ' $LOCATION '
AND `title` LIKE '% $SEARCHTERM %'
OR `content` LIKE '% $SEARCHTERM %'
GROUP BY `posts`.`id`
由于 OR
语句位于末尾,如果在“内容”列中找到匹配项,则该位置将被完全忽略。
是否有办法确保将 WHERE
语句放置在 OR
语句之后?
最佳答案
试试这个:
$this->db->like('title', $term);
$this->db->or_like('content', $term);
$this->db->where('location = ', $location);
$this->db->group_by('posts.id');
$this->db->join('Post_images', 'Post_images.post_id = posts.id');
$query = $this->db->get('posts');
return $query->result_array();
这将重现您预期的查询,但我认为您希望这样的东西能够正常工作:
SELECT *
FROM (`posts`)
JOIN `Post_images` ON `Post_images`.`post_id` = `posts`.`id`
WHERE (`title` LIKE '% $SEARCHTERM %'
OR `content` LIKE '% $SEARCHTERM %')
AND `location` = ' $LOCATION '
GROUP BY `posts`.`id`
注意我添加的括号
要使用事件记录执行此操作,您需要将字符串
传递给where方法,如下所示:
$this->db->where("(`title` LIKE '% $term %' || `content` LIKE '% $term %')");
$this->db->where('location = ', $location);
$this->db->group_by('posts.id');
$this->db->join('Post_images', 'Post_images.post_id = posts.id');
$query = $this->db->get('posts');
return $query->result_array();
让我知道这是否有效
关于php - 使用 codeigniter 的事件记录在 SQL 语句末尾放置 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793188/