views:

37

answers:

3

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(1045):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*

+2  A: 

use HAVING. example:

WHERE
    contents.id > 0   
  AND
    contents.contentType = 'News'
HAVING
    userGroupID = 3
LIMIT 0, 10
oezi
Works fine. Thanks.
Muneer
+1  A: 

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
Dean Harding
Thank you for a different solutions. Works fine.
Muneer
+1  A: 

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
Ignacio Vazquez-Abrams
Good one. It worked.
Muneer