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 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了