作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
谁能帮我转换这个SQL 查询
SELECT *
FROM customer c
LEFT JOIN customer_order co
ON c.customer_number = co.customer_number
AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid'
AND c.order_status = 'unserve'
AND co.cus_ord_no IS null
进入 Codeigniter 查询,例如下图
最佳答案
当查询语句没有需要有条件地更改的子句时,使用 $this->db-query()
是可行的方法。
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co
ON c.customer_number=co.customer_number AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid' AND c.order_status='unserve' AND co.cus_ord_no IS null";
$query = $this->db->query($sql)->result();
echo json_encode($query);
检查 query()
的返回值可能是明智的,因为如果它失败(返回 false),那么对 result()
的调用将抛出异常一个异常(exception)。一种可以处理的方式是这样的。
$query = $this->db->query($sql);
if($query !== FALSE)
{
echo json_encode($query->result());
return;
}
echo json_encode([]); // respond with an empty array
Query Builder (QB) 是一个很好的工具,但它常常有点矫枉过正。创建一个字面上传递给 $db->query()
的字符串会增加很多开销。如果您知道该字符串并且由于某种原因不需要对其进行重组,则您不需要 QB。
当您想有条件地更改查询语句时,QB 最有用。排序可能是一种可能的情况。
if($order === 'desc'){
$this->db->order_by('somefield','DESC');
} else {
$this->db->order_by('somefield','ASC');
}
$results = $this->db
->where('other_field', "Foo")
->get('some_table')
->result();
因此,如果 $order
的值为 'desc'
,则查询语句将为
SELECT * FROM some_table WHERE other_field = 'Foo' ORDER BY somefield 'DESC'
但如果您坚持使用查询生成器,我相信这就是您的答案
$query = $this->db
->join('customer_order co', "c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared')", 'left')
->where('c.customer_status','unpaid')
->where('c.order_status','unserve')
->where('co.cus_ord_no IS NULL')
->get('customer c');
//another variation on how to check that the query worked
$result = $query ? $query->result() : [];
echo json_encode($result);
关于mysql - 如何将 sql 查询转换为 codeigniter 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53416847/
我是一名优秀的程序员,十分优秀!