个性化阅读
专注于IT技术分析

使用WordPress $wpdb获取按2列排序的行结果

我有”交易”表:

id user amount currency plan_id
1   1     11     usd      1
2   1     9      usd      2
3   1     10     usd      2
4   2     10     usd      7
5   1     7      eur      3
6   1     5      eur      3
7   1     6      eur      4
8   3     3      usd      8

我想获取按货币排序的金额总和, 然后按每个给定用户的plan_id:$ results [currency] [plan_id]

$results['usd'][1] = 11
$results['usd'][2] = 19
$results['eur'][3] = 12
$results['eur'][4] = 6

到目前为止, 我有:

$query = '
    SELECT plan_id, currency, SUM( amount ) as earnings
    FROM transactions
    WHERE user = 1
    GROUP BY currency, plan_id
';
$results = $wpdb->get_results( $query, OBJECT_K );

但是它只返回按plan_id定期排序的行, 而忽略按货币排序:

Array ( [1] => stdClass Object ( [plan_id] => 1 [currency] => usd [earnings] => 11 ) [2] => stdClass Object ( [plan_id] => 2 [currency] => usd [earnings] => 19 ) [3] => stdClass Object ( [plan_id] => 3 [currency] => eur [earnings] => 12 ) [7] => stdClass Object ( [plan_id] => 7 [currency] => eur [earnings] => 6 ) ) 

$ wpdb甚至有可能吗?

请帮忙。谢谢


#1


你需要告诉MySQL如何使用ORDER BY子句对结果进行排序(查询中缺少)。

这将产生你想要的结果:

SELECT `plan_id`, `currency`, SUM( `amount` ) AS `earnings`
FROM `transactions`
WHERE `user` = 1
GROUP BY `currency`, `plan_id`
ORDER BY `currency` DESC, `plan_id` ASC
赞(0)
未经允许不得转载:srcmini » 使用WordPress $wpdb获取按2列排序的行结果

评论 抢沙发

评论前必须登录!