我正在寫一個查詢,應該爲每天/每月/每年多個用戶返回聚合小時數。組合SUM(),GROUP_BY()和LEFT_JOIN()返回不正確的結果:如何解決?
表看起來是這樣的:
+------------------------------------------+
| id | entity_id | minutes | person | date |
+------------------------------------------+
如何輸出應該看:
+----------------------------+
| year | month | day | hours |
| 2008 | 12 | 1 | 30 |
| 2008 | 12 | 2 | 40 |
| 2008 | 12 | 3 | 23 |
+----------------------------+
相反,hours
往往很多造成返回的行多因left join
。
問題是我需要根據鏈接到相應實體的標籤查詢此表。當我加入兩個表(提供鏈接的tag_entity
和提供實際標記名稱的tags
)時,我的SUM()
不再有效,因爲返回的結果太多。
查詢:
select
date_format(from_unixtime(date), '%Y-%m-%d') as myDate,
ROUND(SUM(time)/60,1) as hours
from time h
left join tag_entity te on te.entity_id = h.entity_id
left join tags t on t.tag_id = te.tag_id
where (t.tag_name NOT IN ('foo', 'bar', 'baz') OR t.tag_name IS NULL)
group by
myDate
order by
hours DESC, myDate ASC
我該如何解決這個問題?
編輯:
這裏是tag
和tag_entity
的模式:
Tag
:
+----------+-------------+
| Field | Type |
+----------+-------------+
| tag_id | int(11) |
| tag_name | varchar(50) |
+----------+-------------+
而且tag_entity
:
+-----------+---------+
| Field | Type |
+-----------+---------+
| id | int(11) |
| tag_id | int(11) |
| entity_id | int(11) |
+-----------+---------+
也許我還沒有足夠的咖啡,但我無法推斷你的模式。你可以發佈標籤和tag_entity模式的相關部分嗎?另外,在哪個表中定義了「日期」和「時間」? – Andrew 2011-03-18 14:52:39
@Andrew謝謝你的回覆。我添加了模式。 'date'和'time'在我的'時間表'中。 – 2011-03-18 14:58:10
您正在選擇'從t'並執行'left join tag t' - 語法錯誤。你忘了把主表名稱? – 2011-03-18 15:05:46