Compound SQL SELECT

Go To StackoverFlow.com

1

I have the following two tables:

auth_user

  • id
  • username
  • is_active (boolean) ...

useprofile_userprofile

  • id
  • user_id ...

How would I find all auth_user objects where is_active=0 and there is no userprofile_userprofile object with that user_id? For example, an entry like this --

auth_user

  • id = 1
  • username = hello@gmail.com
  • is_active = 0

and userprofile_userprofile has no object where user_id = 1

2012-04-04 07:09
by David542


2

SELECT
    *
FROM
    auth_user
WHERE
    auth_user.is_active=0
    AND NOT EXISTS
        (
            SELECT
                NULL
            FROM
                userprofile_userprofile 
            WHERE
                userprofile_userprofile.user_id=auth_user.id
        )
2012-04-04 07:14
by Arion
+1 Nice use of select nul - joelparkerhenderson 2012-04-04 07:15
Thanks mate. You can have want ever there. SELECT 1 or SELECT 'somevalue'.. But linq-to-sql uses SELECT NULL.. : - Arion 2012-04-04 07:17


3

SELECT *
FROM auth_user A
LEFT JOIN userprofile_userprofile B ON A.id=B.user_id
WHERE A.is_active = false and B.user_id IS NULL

when B.user_id is NULL that means it cannot find a row where user_id=1.
This assumes that the id in table userprofile_userprofile are all not NULL.

2012-04-04 07:16
by cctan
A.is_active = falseDavid542 2012-04-04 07:36
@David542 edited the typ - cctan 2012-04-04 07:43


2

select * from auth_user au
where au.is_active = 0 and 
    not exists(select * from userprofile_userprofile uu where uu.user_id = au.user_id)
2012-04-04 07:13
by Phil


1

Apart from the other solutions you can also do it via LEFT JOIN

SELECT
*
FROM
auth_user au
LEFT JOIN useprofile_userprofile uu ON au.id = uu.user_id
WHERE uu.id IS NULL
AND au.is_active = 0
2012-04-04 07:17
by fancyPants


0

You are looking for Table Joins. Reference this tutorial:

http://www.tizag.com/mysqlTutorial/mysqljoins.php

To answer your question, you are looking for something along the lines of:

"SELECT auth_user.username,auth_user.is_active,useprofile_userprofile.user_id WHERE is_active = 0 AND user_id != 1"

2012-04-04 07:17
by Rob


0

select au.id,au.username,count(up.id) from auth_user au
left outer join useprofile_userprofile up
on au.id=up.user_id
where is_active = 1 
group by au.id,au.username
having count(up.id)=0
2012-04-04 07:19
by Amritpal Singh
Ads