带一个查询的多个求和查询

6xfqseft  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(360)

我想根据products表中的productinformation和producthistory表中的一些字段进行收集如何在单个查询中进行收集?
我的示例代码:

<table> 
    <thead> 
        <tr> 
            <th>Product</th>
            <th>Model</th>
            <th>Actıve Total</th>
            <th>Pasıve Total</th>
            <th>Color Total</th>
        </tr> 
    </thead> 
    <tbody> 
<?php 

$product = $db->get_results("SELECT * FROM product WHERE (status='ACTIVE')");

foreach ($product as $p ){

$active_total   = $db->get_var("SELECT SUM(price) FROM product_history WHERE pid='$p->pid' AND status='AKTIVE'");
$pasive_total   = $db->get_var("SELECT SUM(price) FROM product_history WHERE pid='$p->pid' AND status='PASIVE'");
$color_total    = $db->get_var("SELECT SUM(price) FROM product_history WHERE pid='$p->pid' AND status='ACTIVE' AND color='BLUE'");
?>      
        <tr> 
            <td><?php echo $p->name; ?></td>
            <td><?php echo $p->model; ?></td> 
            <td><?php echo $active_total; ?></td> 
            <td><?php echo $pasive_total; ?></td> 
            <td><?php echo $color_total; ?></td>
         </tr> 
<?php } ?>
    </tbody> 
</table>



谢谢。

jtw3ybtb

jtw3ybtb1#

可以使用条件聚合从一个查询中获取以下结果:

$sql = "SELECT
            SUM(CASE WHEN status='AKTIVE' THEN price ELSE 0 END) AS aktive,
            SUM(CASE WHEN status='PASIVE' THEN price ELSE 0 END) AS pasive,
            SUM(CASE WHEN status='AKTIVE' AND color='BLUE' THEN price ELSE 0 END) AS color,
        FROM product_history 
        WHERE pid='$p->pid'");

实际上,您可以使用 LEFT JOIN :

$sql = "SELECT p.*,
               SUM(CASE WHEN h.status='AKTIVE' THEN h.price ELSE 0 END) AS aktive,
               SUM(CASE WHEN h.status='PASIVE' THEN h.price ELSE 0 END) AS pasive,
               SUM(CASE WHEN h.status='AKTIVE' AND h.color='BLUE' THEN h.price ELSE 0) AS color
        FROM product p
        LEFT JOIN product_history h ON h.pid = p.pid
        WHERE p.status='ACTIVE'
        GROUP BY p.pid";

如果利息的唯一价值来自 productpid (为了与 pid 价值 product_history )你应该换衣服 p.* 在查询中 p.pid . 否则,理想情况下应该枚举需要其值的特定字段。为什么select*被认为是有害的?

piv4azn7

piv4azn72#

我猜你想知道所有的颜色而不仅仅是蓝色?如果那样的话,我会选择 LEFT JOIN ```
SELECT p.pid, p.name, SUM(ph.price) AS total, ph.color, ph.status
FROM product p
LEFT JOIN product_history ph ON (p.pid = ph.pid)
WHERE p.status = 'ACTIVE'
GROUP BY p.pid, p.name, ph.status, ph.color

仅供参考:您应该真正使用准备好的语句来处理上下文更改,并避免任何类型的问题和漏洞。

相关问题