user1046065
user1046065

Reputation: 5

handling null values on select query mysql

table stockholders

stockholder_id    election_id    user_id    
1                 1              1                          
2                 1              2          
3                 2              3         

table users

user_id           user_type
1                 1
2                 1
3                 1
4                 1
5                 1


select 
    * 
from 
    tbl_users
left join tbl_stockholders
    on tbl_stockholders.user_id = tbl_users.user_id
where 
    user_type=1 
    and stockholders.user_id is null 
    and election_id <> 1

i want to search election_id not equal to 1 and user type equal to 1

stockholder_id    election_id    user_id      user_type
3                 2                 3            1         
null              null              4            1
null              null              5            1

this is an update

sorry my problem should be excluding the tbl_stockholders from the tbl_users with the parameter election_id.. because a problem exist when i have a duplicate user_id

table stockholders

stockholder_id    election_id    user_id    
1                 1              1                          
2                 1              2          
3                 2              3   
4                 1              3

in the previous answer this is the result when election_id<>2

stockholder_id    election_id    user_id      user_type
3                 1                 3            1         
null              null              4            1
null              null              5            1

this must be

stockholder_id    election_id    user_id      user_type      
null              null              4            1
null              null              5            1

this is my current not working code

select * from tbl_users where not exists (select * from tbl_stockholders where election_id <> 2)

Upvotes: 0

Views: 1123

Answers (2)

Mosty Mostacho
Mosty Mostacho

Reputation: 43494

Try this:

SELECT * FROM users u
LEFT JOIN stockholders s ON u.user_id = s.user_id
WHERE u.user_type = 1 AND (s.election_id <> 1 OR s.election_id IS NULL)

Fiddle here.

Upvotes: 1

zulqarnain
zulqarnain

Reputation: 1735

I think, this is what you should do: select * from tbl_stockholders left join tbl_users on tbl_users.user_id = tbl_stockholders.user_id where (user_type=1 and election_id <> 1) I don't think you intend to select null user_ids. Also that would invalidate the join i.e you are saying joined the two tables based user_id but select null user_id from the first table.

Upvotes: 0

Related Questions