多个和查询与一个查询

时间:2018-11-01 22:18:06

标签: php mysql sum

我想根据产品表中产品信息和产品历史记录表中的某些字段进行收集,如何在单个查询中做到这一点?

我的示例代码:

    <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>

enter image description here

enter image description here

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合从一个查询中获得这些结果:

$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将两个查询合并为1:

$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";

如果product中唯一感兴趣的值是pid(为了与pid中的product_history值匹配),则应更改{{1} }到p.*的查询中。否则,理想情况下,应枚举所需值的特定字段。参见Why is SELECT * considered harmful?

答案 1 :(得分:1)

我猜你想知道所有的颜色,而不仅仅是蓝色? 在这种情况下,我会选择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

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