MySql Count Query

时间:2009-10-02 15:54:40

标签: sql mysql

我有这个查询,我正在处理一次性报告。基本上我要做的是找到上个月通过一个帐户ID进行两次以上交易的所有记录。我知道这可能很容易,我的想法只是消隐。

SELECT streaming_transactions.account_id,
   streaming_transactions_detail.transactions_description, 
   streaming_transactions_detail.transactions_detail_id, 
   streaming_transactions_detail.transactions_id, 
   streaming_transactions_detail.transactions_detail_amount, 
   streaming_transactions_detail.detail_type, 
   streaming_transactions_detail.products_id, 
   streaming_transactions_detail.products_levels_id, 
   streaming_transactions_detail.subscriptions_id, 
   streaming_transactions_detail.subscriptions_payment_options_id, 
   streaming_transactions_detail.modified
  FROM streaming_transactions_detail 
INNER JOIN streaming_transactions ON  streaming_transactions_detail.transactions_id = streaming_transactions.transactions_id
WHERE streaming_transactions.charged = 1 
  AND streaming_transactions.timestamp_inserted > '2009-09-01 00:00:00'
  AND streaming_transactions.account_id IN (
                 SELECT account_id
                       FROM streaming_transactions_detail
                      WHERE modified > '2009-09-01 00:00:00'
                        AND count(account_id) > 1)
AND streaming_transactions_detail.transactions_description LIKE '%Service Subscription%'
ORDER BY streaming_transactions.account_id DESC

1 个答案:

答案 0 :(得分:3)

我想你差不多了。 获取事务ID的子查询已关闭,但是

         SELECT account_id
              FROM streaming_transactions_detail
              WHERE modified > '2009-09-01 00:00:00'
              AND count(account_id) > 1)

- 应该像

         SELECT account_id, COUNT(account_id)
             FROM streaming_transactions_detail
             WHERE modified > '2009-09-01 00:00:00'
             GROUP BY account_id
             HAVING count(account_id) > 1)

[无关]我会提出一个关于风格的未经请求的暗示 通过使用表别名,您可以提高查询的可读性。这可以通过选择添加“AS xyz”来完成,其中xyz是一些简短的助记符名称,对于此查询而言是唯一的,您可以在查询中的任何位置使用xyz来使用long_named_table。
例如:

FROM streaming_transactions_detail AS D

然后

SELECT streaming_transactions.account_id,
   streaming_transactions_detail.transactions_description, 
   streaming_transactions_detail.transactions_detail_id, 
   ...

可以成为(可选地,即“streaming_transactions_detail。”仍然有效)

SELECT D.account_id,
   D.transactions_description, 
   D.transactions_detail_id, 
   ...