MySQL: return “0” & “1” rather than “false” & “true”

前端 未结 4 1004
抹茶落季
抹茶落季 2021-01-20 10:54

I need to return true or false rather than 1 & 0, using following query:

select if(u.id is null,false         


        
相关标签:
4条回答
  • 2021-01-20 11:06

    TRUE/FALSE is equivalent to 1/0. It's just a matter of how your front end displays it.

    If you need to return the strings "true" and "false" (which I don't suggest - handle that in the display) then you'll have to account for that as well:

    IF(IF(u.id ISNULL,false,true) = 1, 'TRUE', 'FALSE')

    0 讨论(0)
  • 2021-01-20 11:21

    IF()

    You are missing single quotes.

    select if(u.id is null,'false','true') status
    from user u
    limit 10;
    
    0 讨论(0)
  • 2021-01-20 11:24

    MySQL has no boolean datatype, so you need to stick with 0 and 1 on the MySQL side:

    select if(u.id is null, 0, 1) status_int
    from user u
    limit 10
    

    If you prefer a boolean over 0/1 in PHP, you can cast it like this:

    $status = (bool) $status_int;
    
    0 讨论(0)
  • 2021-01-20 11:25

    If you want, you can return the values as strings:

    SELECT IF(u.id IS NULL, 'false', 'true') as status
    FROM user u
    LIMIT 10
    
    0 讨论(0)
提交回复
热议问题