How to check if a given data exists in multiple tables (all of which has the same column)?

后端 未结 6 1218
眼角桃花
眼角桃花 2020-12-06 05:48

I have 3 tables, each consisting of a column called username. On the registration part, I need to check that the requested username is new and unique.

I need that si

6条回答
  •  广开言路
    2020-12-06 06:24

    Given the collation stuff, you could do this instead, if you don't want to deal with the collation mismatch:

    select sum(usercount) as usercount
    from (
        select count(*) as usercount from tbl1 where username = 'someuser'
        union all
        select count(*) as usercount from tbl2 where username = 'someuser'
        union all
        select count(*) as usercount from tbl3 where username = 'someuser'
    ) as usercounts
    

    If you get 0, there isn't a user with that username, if you get something higher, there is.

    Note: Depending on how you do the insert, you could in theory get more than one user with the same username due to race conditions (see other comments about normalisation and unique keys).

提交回复
热议问题