如何使用嵌套别名使查询更简单?
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
结果将是 Y
或 N
,而您在下一个测试中检查 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
【讨论】:
以上是关于如何使用嵌套别名使查询更简单?的主要内容,如果未能解决你的问题,请参考以下文章