How to use MYSQL's "AS" returned value inside WHERE clause?
I have a query开发者_运维技巧 like below...
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
When I try to assign the userGroupID inside WHERE clause the SQL fires an error saying SQL Error(1054):Unknown column "userGroupID" in "where clause"
meantime, if I make little changes like below,,
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
then the query works fine.
I have to use multiple userGroupID checking so that, 2nd style will make the query big, I have to have an style like first one, any help appreciated.
*NOTE : Table names are not original name what I am using in my project. You may ignore it if there are mistakes in table name. My main concern is on using the values assign to a variable by AS inside the WHERE clause.
Ignore the STARS in query*
use HAVING
. example:
WHERE
contents.id > 0
AND
contents.contentType = 'News'
HAVING
userGroupID = 3
LIMIT 0, 10
If I'm understanding your initial query properly, then I believe what you want to do is a join:
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
Totally not the answer to the question you asked, but...
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
精彩评论