1

我在同一个表上为两个不同的选择语句使用两个连接。我想实现一个 IF 函数,由于表可能包含零,我想用零替换单词“None”

这是我的有效 SQL:

SELECT
CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`) AS `AssignedTo`,
CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
FROM `mb_payments` as `payments`
LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`

这是我的 IF 函数不起作用的 SQL:

SELECT
IF(AssignedTo IS 0,'None', CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`)),
CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
FROM `mb_payments` as `payments`
LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`
4

2 回答 2

2

我认为您想要“.. = 0”,而不是“... IS 0”。与 NULL 比较时使用 IS。

于 2012-04-10T17:20:29.430 回答
2

在这种情况下,您可以使用 CASE 语句,或者如果您想使用 IF 语句,那么您的语句是错误的。它应该是:

SELECT

    IF(AssignedTo = 0,'None', CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`)) AS Result,
    CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
    FROM `mb_payments` as `payments`
    LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
    LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`

看看这个博客:http ://timmurphy.org/2009/08/13/inline-if-and-case-statements-in-mysql/

于 2012-04-10T17:23:37.907 回答