【问题标题】:How to use nested alias to make the query simpler?如何使用嵌套别名使查询更简单?
【发布时间】:2018-04-22 17:24:47
【问题描述】:

假设我有这个查询:`

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

注意上面的语法是否正确。

【问题讨论】:

  • 你需要使用子查询。

标签: php mysql sql pdo alias


【解决方案1】:

试试这个:

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 将是 Not Great 对于所有行。

您的查询应该是:

SELECT
    Manage,
    dCheck,
    firstNested,
    IF(firstNested="Great",1,0) AS secondNested
FROM
(
    SELECT
        Manage,
        dCheck,
        IF(dCheck="Y", "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

【讨论】:

    猜你喜欢
    • 2019-04-01
    • 2017-06-15
    • 2023-01-03
    • 2013-08-23
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2014-05-21
    相关资源
    最近更新 更多