我在 codeigniter 中使用以下查询:
$this->db->select('products.id,
categories.name as cat_name,
products.name as name,
products.product_image,
products.description,
products.price,
products.furl,
products.on_sale,
products.quantity_in_stock,
products.product_code,
products.rating_1,
products.rating_2,
products.rating_3,
products.rating_4,
products.rating_5,
products.rated_by,
products.discount,
((products.rating_1+products.rating_2,
products.rating_3,
products.rating_4,
products.rating_5)/rated_by as calc)
');
检查 calc 附近的 sql 语法时出现错误。请解释问题出在哪里以及原因。 p.s:我只是想在 order by 子句中使用 calc,如下所示:
$this->db->order_by('calc','desc');
$this->db->get();
更新:这是我在执行此查询时得到的结果:
Error Number: 1064
您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的 'as calc) FROM (
products
) JOIN categories
ON categories
.id
=products
.`ca' 附近使用的正确语法
如果您要使用别名,那么您将不希望 CodeIgnioter 自动在您的列名称周围添加勾号,因为它会破坏一切。只需将
select()
的第二个参数设置为 false
即可关闭此行为:
$this->db->SELECT(
'products.id,categories.name as cat_name,
products.name as name,
products.product_image,
products.description,
products.price,
products.furl,
products.on_sale,
products.quantity_in_stock,
products.product_code,
products.rating_1,
products.rating_2,
products.rating_3,
products.rating_4,
products.rating_5,
products.rated_by,
products.discount,
((products.rating_1+products.rating_2,
products.rating_3,products.rating_4,
products.rating_5)/rated_by as calc)', false) ;
是的,你是对的@John
$this->db->select('
products.id,
categories.name as cat_name,
products.name as name,
products.product_image,
products.description,
products.price,
products.furl,
products.on_sale,
products.quantity_in_stock,
products.product_code,
products.rating_1,
products.rating_2,
products.rating_3,
products.rating_4,
products.rating_5,
products.rated_by,
products.discount,
(
(products.rating_1 + products.rating_2,
products.rating_3,
products.rating_4,
products.rating_5
)
/ rated_by as calc
)
', false) ;
也为我工作