简体   繁体   中英

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

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.

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

How about listing the values that are 1 ?

SELECT CONCAT_WS(',', 
                 (CASE WHEN EXISTS (select 1 from user where username = 'rahim') THEN 'USER' END),
                 (CASE WHEN EXISTS (select 1 from `group` where group_name = 'rahim') THEN 'GROUP' END)
                )

As for only selecting columns that have a 1 -- you cannot do that with a single query because a query returns a fixed set of columns. What you can do (as above) is return a value that has the column names you are looking for.

Use UNION ALL with NOT EXISTS :

select uid from `group` 
where group_name = 'rahim'
union all
select user_id from `user` 
where username = 'rahim'
and not exists (select 1 from `group` where group_name = 'rahim')

See the demo .
Results:

| uid     |
| ------- |
| 1       |

Try this:

select * from (select case when 'rahim'=(select username from user1 where username='rahim') then 1 else 0 
end as user_id,
case when 'rahim'=(select group_name  from group1 where group_name ='rahim') then 1 else 0 
end as group_id)t; --Here you can put the filtration condition. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM