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

Posted

技术标签:

【中文标题】如何使用嵌套别名使查询更简单?【英文标题】: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

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

【问题讨论】:

你需要使用子查询。 【参考方案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

【讨论】:

以上是关于如何使用嵌套别名使查询更简单?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用媒体查询或运算符使 SASS 嵌套嵌套媒体查询工作

如何使从 oracle 返回的结果集保持其列别名字符大小写

VF中SQl语句中的select语句如何使用……

如何使这个联合查询更有效率?

PHP 循环遍历嵌套的 JSON 响应并重新组装为 Webhook 的简单查询字符串

如何使用 Laravel 的查询构建器执行嵌套连接?