gpt4 book ai didi

mysql - 如何将 sql 查询转换为 codeigniter 查询

转载 作者:行者123 更新时间:2023-11-29 01:35:04 25 4
gpt4 key购买 nike

谁能帮我转换这个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 查询,例如下图

enter image description here

最佳答案

当查询语句没有需要有条件地更改的子句时,使用 $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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com