2010-06-30 75 views
1

我在我的select子句(AVG(u.rating) as avg_rating)中使用了一個別名,然後希望將其添加到我的where子句avg_rating > 3中,但是當我嘗試運行此查詢時,我得到Unknown column 'u3__1' in 'where clause'來自where子句中的select子句的原則和別名

有沒有人碰巧知道如何讓我的where子句看到別名?這個別名在orderBy中沒有問題,只是不是where

編輯:(詳情)

上面就是一個例子,但這裏是真正的渲染SQL,不是那麼簡單。我的問題實際上是在一系列條件下帶有別名。而我遇到的別名是生成的日期,它具有重複性,並且不必填寫每個日期字段。所以我發佈了一個簡單的SQL查詢,給了我同樣的問題。

SELECT t.type_id as type_alias, t.* FROM theme as t WHERE t.id > 1 AND type_alias = 3 

這裏是真正的查詢,如果你這麼有興趣:

SELECT t.id AS t__id, t.created_by AS 
t__created_by, t.type_id AS 
t__type_id, t.url_slug AS t__url_slug, 
t.name AS t__name, t.description AS 
t__description, t.summary AS 
t__summary, t.start_month AS 
t__start_month, t.start_day AS 
t__start_day, t.start_year AS 
t__start_year, t.duration_unit AS 
t__duration_unit, t.duration_length AS 
t__duration_length, t.is_active AS 
t__is_active, t.is_public AS 
t__is_public, t.needs_moderation AS 
t__needs_moderation, t.recurrence AS 
t__recurrence, t.tag_string AS 
t__tag_string, t.date_created AS 
t__date_created, t.date_updated AS 
t__date_updated, AVG(t2.rating) AS 
t2__0, IF(t.recurrence = "none", 
STR_TO_DATE(CONCAT(t.start_month, 
t.start_day, t.start_year), "%m%d%Y"), 
(IF(STR_TO_DATE(CONCAT(t.start_month, 
t.start_day, YEAR(NOW())), "%m%d%Y") > 
NOW(), 
STR_TO_DATE(CONCAT(t.start_month, 
t.start_day, YEAR(NOW())), "%m%d%Y"), 
STR_TO_DATE(CONCAT(t.start_month, 
t.start_day, (YEAR(NOW())+1)), 
"%m%d%Y")))) AS t__1, (COUNT(u.id) + 
COUNT(e.id)) AS u__2 FROM theme t LEFT 
JOIN theme_rating t2 ON t.id = 
t2.theme_id LEFT JOIN 
user_saves_themes u ON t.id = 
u.theme_id LEFT JOIN event e ON 
((e.is_active = 1 AND e.theme_id = 
t.id)) WHERE t.id IN ('3', '2', '1') 
AND (IF(t.recurrence = "none", 
STR_TO_DATE(CONCAT(t.start_month, 
t.start_day, t.start_year), "%m%d%Y"), 
(IF(STR_TO_DATE(CONCAT(t.start_month, 
t.start_day, YEAR(NOW())), "%m%d%Y") > 
NOW(), 
STR_TO_DATE(CONCAT(t.start_month, 
t.start_day, YEAR(NOW())), "%m%d%Y"), 
STR_TO_DATE(CONCAT(t.start_month, 
t.start_day, (YEAR(NOW())+1)), 
"%m%d%Y")))) >= 
FROM_UNIXTIME(1278001295) AND 
t.is_public = ? AND t.is_active = ?) 
GROUP BY t.id ORDER BY t__1 
+0

好的,很確定這可能是由於SELECT發生在WHERE之後,但仍不確定如何解決此問題。 – gokujou 2010-06-30 19:27:59

+0

我們可以看到整個*生成的*查詢嗎? (假設你正在使用查詢生成器而不是手動編寫SQL,Doctrine和所有這些。) – Charles 2010-06-30 20:04:19

+0

你試過 - > where(「AVG(u.rating)> 3」)...? – Tom 2010-06-30 21:21:13

回答

1

嘗試具有替代的位置。

+0

雖然這可能會在某些情況下解決問題,但這可能不是您想要的。 'HAVING'在'WHERE'之後運行,並且取決於'WHERE'排除了多少行,性能可能會大幅下降。 – Charles 2010-06-30 20:05:44

+0

是的,動態查詢相當複雜,嘗試HAVING不能很好地工作。 – gokujou 2010-07-01 16:32:50