dqy27359 2011-10-20 17:33
浏览 45
已采纳

mysql交叉表查询到php数组 - 而不是三个sql查询

I'd like to select sum of three columns from three tables in mysql and then get it as php array.

Tables:

Amex:
incr_id,check_no, card_no, tip, total, date;
Mc:
incr_id,check_no, card_no, tip, total, date;
Visa
incr_id,check_no, card_no, tip, total,date ;

Pseudo code :

 $query = 
 select sum(tip) from Amex,
 select sum(tip) from Mc,
 select sum(tip) from Visa
 WHERE DATE(date) = CURDATE()

 mysql_fetch_array($query);

and then 'foreach' or 'while' to get three values into php array:

$ccpayments_tip['Amex']
$ccpayments_tip['Mc']      
$ccpayments_tip['Visa']

Is this possible or I will have to execute three select queries? Thanks!

  • 写回答

3条回答 默认 最新

  • doulan9188 2011-10-20 17:39
    关注

    You can use a Union query to do all three at once, with a derived field to indicate which table the sums are coming from:

    $sql = <<<EOL
    SELECT 'Amex' AS source, SUM(tip) AS sum FROM Amex
    UNION
    SELECT 'MC' AS source, SUM(tip) AS sum FROM Mc
    UNION
    SELECT 'Visa' AS source, SUM(tip) AS sum FROM Visa
    
    EOL;
    
    $result = mysql_query($sql) or die(mysql_error());
    
    $ccpayments_tip = array();
    while($row = mysql_fetch_assoc($result)) {
        $ccpayments_tip[$row['source']] = $row['sum'];
    }
    

    Of course, why do you have 3 seperate tables for this? Wouldn't it make more sense to have a single creditcard table with a type field to indicate if it's visa/amex/mc?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab