2009-10-02 167 views
1

我有這個查詢,我正在爲一次性報告工作。基本上我試圖做的是找到所有的記錄,上個月有一個帳戶ID有兩個以上的交易。我知道這可能是一件容易的事,我的想法只是空白。MySql計數查詢

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 
+0

哪些錯誤與您的查詢,是您得到不正確的結果或錯誤? – 2009-10-02 15:59:41

+0

我收到一個錯誤。看起來你不能在WHERE子句中有count(),但是在HAVING子句中 – 2009-10-02 16:08:17

回答

3

我想你幾乎就在那裏。 子查詢,以獲得交易IDS是關閉的,但是

  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是一些簡短但助記符的名稱,對於此查詢是唯一的,您可以在查詢中使用x_name的任何位置使用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, 
    ... 
+0

這正是我所需要的。有! – 2009-10-02 16:07:35

+0

我完全理解別名。這是對一次性報告的丟棄查詢。只需運行一次即可找到我們遇到的問題。通常情況下,查詢看起來會有很大的不同。但我真的很感激它。 – 2009-10-02 16:13:58