Search code examples
mysqlsqlmysql-error-1054

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*


Solution

  • 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