用于子查询的MySQL IF语句

时间:2016-04-07 18:14:29

标签: mysql sql if-statement subquery

我正在尝试用MySQL语言(if语句的一部分)来实现这个例子..任何人都可以尝试帮助我吗?我已经被困了几天了。

SELECT * FROM tblUsers

INNER JOIN
    IF function <= 1
    (
        // SELECTING ALL IF THE USERS FUNCTION TOLERATES IT (HAS PRIVILEGE TO IT)
        SELECT * FROM tblDomains
    )
    ELSE
    (
        // SELECTING A SPECIFIC VALUE
        SELECT * FROM tblDomains WHERE domain = 'example.com'
    )
ON (part continues here, ofcourse)

WHERE username = :name AND password = :password

/ *更新的代码* /

(咳嗽IS NULL而不是= NULL,解决了我的问题)

SELECT * FROM strix_users
LEFT JOIN strix_userstodomains
ON strix_users.users_id = strix_userstodomains.userstodomains_user
INNER JOIN strix_domains
ON (users_id = 1 AND users_password = 'lol' AND users_function <= 1)
OR (users_id = 1 AND users_password = 'lol' AND users_function > 1 AND userstodomains_domain > 0 AND strix_userstodomains.userstodomains_domain = strix_domains.domain_id)
OR (users_id = 1 AND users_password = 'lol' AND users_function > 1 AND userstodomains_domain = NULL AND domain_name = 'strix-it.local')

2 个答案:

答案 0 :(得分:2)

像这样的东西

SELECT * 
FROM   tblusers 
       INNER JOIN tbldomains tb 
               ON ( username = :name 
                    AND password = :password 
                    AND function <= 1 ) 
                   OR ( username = :name 
                        AND password = :password 
                        AND domain = 'example.com' 
                        AND function > 1 ) 

答案 1 :(得分:0)

我会把它写成:

SELECT * 
FROM tblusers u INNER JOIN
     tbldomains td 
     ON . . . 
WHERE u.username = :name AND u.password = :password AND
      (COALESCE(@function, 0) <= 1 OR td.domain = 'example.com') ;

注意:您应该以不会与列名冲突的方式命名变量。我将function更改为@function。但这也可以写成v_function