2010-07-19 56 views
1

我有一個查詢像下面...如何在WHERE子句中使用MYSQL的「AS」返回值?

SELECT 
    contents.id, contents.title, contents.createdBy, 
(SELECT userGroup FROM suser_profile WHERE userId = 
     (SELECT users.id 
      FROM 
      users 
      WHERE 
      login = contents.createdBy) 
    ) as userGroupID 
FROM 
    contents 
WHERE 
    contents.id > 0 
    AND contents.contentType = 'News' 
    **AND userGroupID = 3** 
LIMIT 0, 10 

當我嘗試分配userGroupID內WHERE子句的SQL觸發一個錯誤說SQL錯誤(1054):未知列「userGroupID」在「哪裏條款」

與此同時,如果我做變化不大像下面,,

SELECT 
    contents.id, contents.title, contents.createdBy 
FROM 
    smart_cms_contents 
WHERE 
    contents.id > 0 
    AND contents.contentType = 'News' 
    **AND (SELECT userGroup FROM user_profile WHERE userId = 
     (SELECT users.id 
      FROM 
      users 
      WHERE 
      users.login = contents.createdBy) 
    ) = 3** 
LIMIT 0, 10 

那麼查詢工作正常。

我必須使用多個userGroupID檢查,以便第二種風格會使查詢大,我必須有一個樣式像第一個,任何幫助讚賞。

*注意:表名不是我在項目中使用的原始名稱。如果表名中有錯誤,您可以忽略它。我主要關心的是如何在WHERE子句中使用AS賦值給一個變量。

忽略STARS查詢*

回答

1

如果我正確理解你的初始查詢,那麼我相信你想要做什麼是加盟:

SELECT DISTINCT 
    contents.id, contents.title, contents.createdBy 
FROM 
    contents INNER JOIN users 
     ON contents.createdBy = users.login 
    INNER JOIN user_profile 
     ON user_profile.userId = users.id 
WHERE 
    contents.id > 0 
    AND contents.contentType = 'News' 
    AND user_profile.userGroupID = 3 
LIMIT 0, 10 
+0

感謝您使用不同的解決方案。工作正常。 – BlueBird 2010-07-19 07:51:18

2

使用HAVING。例如:

WHERE 
    contents.id > 0 
    AND 
    contents.contentType = 'News' 
HAVING 
    userGroupID = 3 
LIMIT 0, 10 
+0

工作正常。謝謝。 – BlueBird 2010-07-19 07:52:26

1

完全不是回答你問的問題,但。 ..

SELECT DISTINCT c.id, c.title, c.createdBy, s.userGroup AS userGroupID 
FROM contents AS c 
INNER JOIN users AS u 
    ON c.createdBy = u.login 
INNER JOIN suser_profile AS s 
    ON s.userId = u.id 
WHERE c.id > 0 
    AND c.contentType = 'News' 
    AND s.userGroup = 3 
+0

好的。有效。 – BlueBird 2010-07-19 07:55:23

相關問題