我有一个现有的SQL查询,可以完全按照我的意愿运行:
$this->db->select('places.*, category.*')
->select('COUNT(places_reviews.place_id) AS num_reviews')
->select('(places_popularity.rating_1 + 2*places_popularity.rating_2 + 3*places_popularity.rating_3 + 4*places_popularity.rating_4 + 5*places_popularity.rating_5)/(places_popularity.rating_1 + places_popularity.rating_2 + places_popularity.rating_3 + places_popularity.rating_4 + places_popularity.rating_5) AS average_rating')
->from('places')
->join('category', 'places.category_id = category.category_id')
->join('places_reviews', 'places_reviews.place_id = places.id', 'left')
->join('places_popularity', 'places_popularity.place_id = places.id', 'left')
->where('places.category_id', $category_id)
->group_by('places.id')
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
但是现在我想通过在上面添加一行来为查询添加一个LIKE子句来获取:
$this->db->select('places.*, category.*')
->select('COUNT(places_reviews.place_id) AS num_reviews')
->select('(places_popularity.rating_1 + 2*places_popularity.rating_2 + 3*places_popularity.rating_3 + 4*places_popularity.rating_4 + 5*places_popularity.rating_5)/(places_popularity.rating_1 + places_popularity.rating_2 + places_popularity.rating_3 + places_popularity.rating_4 + places_popularity.rating_5) AS average_rating')
->from('places')
->join('category', 'places.category_id = category.category_id')
->join('places_reviews', 'places_reviews.place_id = places.id', 'left')
->join('places_popularity', 'places_popularity.place_id = places.id', 'left')
->where('places.category_id', $category_id)
->like('places.name', $term)
->group_by('places.id')
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
然而,它给我的结果不准确。例如,当我让字符串被搜索时$ term =“hong”而我有3行,其中'name'列匹配“hong”即。 (香港咖啡厅,香港咖啡厅,拉面红),我只会(香港咖啡厅,香港咖啡厅)退货。现在,如果$ term =“hong kong”,我只回来了一个'香港咖啡馆'而不是两个。
另一个让我更进一步困惑!有一排叫做“Dozo”。当$ term ='dozo'时,不会返回任何结果!
为什么会发生这种情况?
生成实际SQL 对不起,它出现在第1行
SELECT `places`.*, `category`.*, COUNT(places_reviews.place_id) AS num_reviews, (places_popularity.rating_1 + 2*places_popularity.rating_2 + 3*places_popularity.rating_3 + 4*places_popularity.rating_4 + 5*places_popularity.rating_5)/(places_popularity.rating_1 + places_popularity.rating_2 + places_popularity.rating_3 + places_popularity.rating_4 + places_popularity.rating_5) AS average_rating FROM (`places`) JOIN `category` ON `places`.`category_id` = `category`.`category_id` LEFT JOIN `places_reviews` ON `places_reviews`.`place_id` = `places`.`id` LEFT JOIN `places_popularity` ON `places_popularity`.`place_id` = `places`.`id` WHERE `places`.`category_id` = 1 AND `places`.`name` LIKE '%Dozo%' GROUP BY `places`.`id` ORDER BY `average_rating` desc LIMIT 1, 3
更新
解决。它是一个将错误的变量传递给LIMIT子句的分页问题。谢谢!
答案 0 :(得分:3)
从您的实际查询中,offset
从1
而不是0
开始,这样就会忽略第一条记录(偏移0
)。
因此:
另一个让我更进一步困惑! 有一排叫做“Dozo”。什么时候 $ term ='dozo',没有结果返回!
显然不会返回任何内容。