gpt4 book ai didi

php - MYSQL 嵌套查询

转载 作者:行者123 更新时间:2023-11-29 08:21:19 24 4
gpt4 key购买 nike

问这个问题的目的只是为了学习如何在MYSQL中进行嵌套查询。

1) 以下查询有什么问题?

"SELECT tblwriter.writer_alias, tblwriter.writer_first_name, COUNT(tblordersub.suborder_alias) AS totalOrders FROM tblwriter, tblordersub WHERE tblwriter.writer_isactive = 1 AND tblordersub.writer_alias = tblwriter.writer_alias"

2)对于下面的MYSQL查询嵌套是否有更好的解决方案?

$currentorders = $db->rawQuery("SELECT order_title,order_alias FROM tblorder WHERE company_id=? AND YEAR(order_date) = YEAR(CURDATE()) AND MONTH(order_date) = MONTH(CURDATE())",$params);
$orderssummary = array();
if(!empty($currentorders)){
foreach($currentorders as $corder){
$param = array($corder["order_alias"]);
$oprice = $db->rawQuery("SELECT payment_amount FROM tblpayment WHERE payment_status = 1 AND writer_alias IS NULL AND order_alias=?",$param);
$itssuborders = $db->rawQuery("SELECT suborder_alias FROM tblordersub WHERE order_alias=?",$param);
$thesuborders = array_implode("",",",$itssuborders);
$cost = $db->rawQuery("SELECT SUM(payment_amount) AS total_subtotal FROM tblpayment WHERE writer_alias IS NOT NULL AND suborder_alias IN (".$thesuborders.")");
$orderssummary[] = array("title"=>$corder["order_title"],"price"=>$oprice[0]["payment_amount"],"cost"=>$cost[0]["total_subtotal"]);
}
}

3)有没有办法将以下三个查询合并为1个?

"SELECT SUM(payment_amount) AS totalAmount FROM tblpayment WHERE company_id=? AND payment_status = 1 AND order_alias IS NOT NULL AND YEAR(payment_add_datetime) = YEAR(CURDATE()) AND MONTH(payment_add_datetime) = MONTH(CURDATE() - INTERVAL 2 MONTH)"
"SELECT SUM(payment_amount) AS totalAmount FROM tblpayment WHERE company_id=? AND payment_status = 0 AND writer_alias IS NOT NULL AND YEAR(payment_add_datetime) = YEAR(CURDATE()) AND MONTH(payment_add_datetime) = MONTH(CURDATE() - INTERVAL 2 MONTH)"
"SELECT SUM(payment_amount) AS totalAmount FROM tblpayment WHERE company_id=? AND payment_status = 1 AND writer_alias IS NOT NULL AND YEAR(payment_add_datetime) = YEAR(CURDATE()) AND MONTH(payment_add_datetime) = MONTH(CURDATE() - INTERVAL 2 MONTH)"

4)与第二个问题相同,有没有办法将以下查询合并为1个查询?

$biggest_customers = $db->rawQuery("SELECT payment_user_id, SUM(payment_amount) AS totalEARNED FROM tblpayment WHERE writer_alias IS NULL AND order_alias IS NOT NULL GROUP BY payment_user_id ORDER BY totalEARNED DESC LIMIT 10");
for($i=0;$i<count($biggest_customers);$i++){
$params = array($biggest_customers[$i]["payment_user_id"]);
$customerinformation = $db->rawQuery('SELECT customer_alias FROM tblcustomer WHERE user_id=?',$params);
$biggest_customers[$i]["customer_alias"] = $customerinformation[0]["customer_alias"];
unset($biggest_customers[$i]["payment_user_id"]);
}

希望能学到一些东西!

最佳答案

  1. 查看聚合查询
  2. 查看 JOIN
  3. 请参阅 CASE 语句/数据透视表查询
  4. 再次查看“加入”

关于php - MYSQL 嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19322866/

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