mysql query get data from table b if not exist in table a

Premlatha :

I have two tables, group and user. I want to get id of username='rahim' from sql table. If username='rahim' exist in table group, then get id from table group. Else if exist in table user, then get id from table user.

Table user

user_id|username
1      |rahim
2      |hemala

Table group

uid    |group_name
1      |A
2      |B

Query

SELECT 
EXISTS(select * from user where username='rahim') as user_id,
EXISTS(select * from `group` where group_name='rahim') as group_id

result:

user_id | group_id
      1 |        0

If exist, it show 1. This 1 refer to existence. 1:exist , 0:not exist . I want to filter the columns which is equal to 1 only and show id of the user which is also 1.

Expected result:

user_id 
    1    

This 1 refer to id.

Thanks in advance.

parisam :

The IF() function returns a value if a condition is TRUE, or another value if a condition is FALSE.

IF(condition, value_if_true, value_if_false)

this query get you the id

SELECT IF(user_id IS NULL , group_id, user_id) as id from (
    SELECT 
    (select id from user where username='rahim') as user_id, 
    (select uid from group where group_name='rahim') as group_id
    ) as temp

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169931&siteId=1