如何使用嵌套别名使查询更简单?

时间:2018-04-22 17:24:47

标签: php mysql sql pdo alias

让我说我有这个问题:`

SELECT
    IF(uPer="Yes", "Y", "N") AS Manage,
    IF(date_check="Yes", "Y", "N") As dCheck,
    IF(dCheck="Yes", "Great", "Not Great") AS firstNested,
    IF(firstNested="Great",1,0) AS secondNested
FROM table

所以在这个例子中我有更多的1个别名,我想在其他别名中使用其中一些,就像嵌套的别名一样。

如何在不复制/粘贴别名的情况下实现此目的,例如:

IF(
   IF(dCheck="Yes", "Great", "Not Great") AS firstNested) ="Great",1,0
) AS secondNested

请注意以上是否是正确的语法。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
    Manage,
    dCheck,
    firstNested,
    IF(firstNested="Great",1,0) AS secondNested
FROM
(
    SELECT
        Manage,
        dCheck,
        IF(dCheck="Yes", "Great", "Not Great") AS firstNested
    FROM
    (
        SELECT
            IF(uPer="Yes", "Y", "N") AS Manage,
            IF(date_check="Yes", "Y", "N") As dCheck
            FROM table
    ) as t1
) as t2

错误:dCheck结果将是YN,您在下一个测试中检查Yes将导致错误,firstNested将{所有行都是{1}}。

您的查询应该是:

Not Great