在一个表中多次选择

时间:2018-04-26 09:07:10

标签: mysql

我的问题是如何使用PHP和MySQL在一个表中选择使用多个选择查询。我试着使用distinct或union但没什么!

以下是表中的一部分:

ticket|amount
1357  | 5 
1357  | 5 
1356  | 10 
1356  | 10 
1356  | 10 
1355  | 5 
1355  | 5 
1355  | 5 
1354  | 5 
1354  | 5

我需要像这样的结果

1357 -> 5 
1356 -> 10 
1355 -> 5 
1354 -> 5

total tickets -> 4 
total_amount -> 25

4 个答案:

答案 0 :(得分:1)

似乎你正在寻找票据

的max(),count()和sum()
  select ticket, max(amount), count(*), sum(amount)
  from my_table  
  group by ticket 

或者如果您需要最大值之和

select count(*), sum(my_max)
from (
  select ticket, max(amount) my_max, count(*), sum(amount) 
  from my_table  
  group by ticket ) t 

答案 1 :(得分:0)

SELECT CAST(`ticket` AS CHAR(10)) AS ticket,`amount` FROM Table1 
GROUP BY `ticket`,`amount`
UNION ALL
SELECT 'total tickets' AS ticket,COUNT(*) as amount 
FROM (
        SELECT CAST(`ticket` AS CHAR(10)) AS ticket,`amount` FROM Table1
        GROUP BY `ticket`,`amount`
     ) T1
UNION ALL
SELECT 'total_amount' AS ticket,SUM(amount) as amount 
FROM (
        SELECT CAST(`ticket` AS CHAR(10)) AS ticket,`amount` FROM Table1
        GROUP BY `ticket`,`amount`
     ) T2

<强>输出

ticket          amount
1354            5
1355            5
1356            10
1357            5
total tickets   4
total_amount    25

<强>演示

  

http://sqlfiddle.com/#!9/03a0d/47

答案 2 :(得分:0)

下面的代码在oracle中工作,使用了cast运算符,这样我就可以使用union来获取输出中的文本。

select distinct ticket ticket,cast (amount as varchar2(200)) as amount
from test_ticket 
union
select 'number of ticket->'|| cast(count(ticket) as varchar2(200)) as  
ticket,'sum of amount->'||sum(amount) as amount
from (
select distinct ticket,amount
from test_ticket);

答案 3 :(得分:0)

如果我理解你需要->是一个关联数组吗?在这种情况下,请像这样:

SELECT `ticket`, `amount` FROM `test_ticket` GROUP BY `ticket`, `amount`

这是用于创建所需数组的PHP代码:

// query and constuct array
if($data = $db->query($q) {
    if($arr = $data->fetchAll(MYSQL_FETCH_ASSOC)) {
        foreach($arr as $res) {
            $output[$res['ticket']]  = $res['amount'];
            $output['total_tickets'] ++;
            $output['total_amount']  += $res['amount'];
        }
    }
}

// to print the array
print_r($output);