我正在尝试在SQL查询上创建一个子选择,如下所示:
SELECT
t0.id, t0.gad, t0.gbd, t0.mandant, t0.gbd, t1.year
FROM
person t0
LEFT OUTER JOIN
control t1 ON (t0.id = t1.id)
WHERE
((t0.id = '1') or (t0.id = '2'));
您可以看到有两列相同的列gbd
。但是,此查询成功运行。但是当我尝试将此查询用作下面的子选择时,它会失败,返回错误#8156
:
SELECT *
FROM
(SELECT
t0.id, t0.gad, t0.gbd, t0.mandant, t0.gbd, t1.year
FROM
person t0
LEFT OUTER JOIN
control t1 ON (t0.id = t1.id)
WHERE ((t0.id = '1') or (t0.id = '2'))) result
WHERE
(result.gad >= 0) and (result.gbd <= 99);
我知道选择同一列两次实际上没有任何意义,但我无法更改内部SQL查询,因为我只是从数据库中读取它。
此查询的目标是仅获取特定范围内的结果。
所以我的问题是,如何在不更改内部SELECT
语句的情况下使此查询工作?这也意味着我不知道列,因此我无法将*
更改为特定的列名。
答案 0 :(得分:2)
你需要给它一个别名。子查询不能有两个具有相同名称的列:
SELECT *
FROM (SELECT t0.id, t0.gad, t0.gbd as gbd, t0.mandant, t0.gbd as gbd1, t1.year
FROM person t0 LEFT OUTER JOIN control t1 ON (t0.id = t1.id)
WHERE ((t0.id='1') or (t0.id='2'))
) result
WHERE (result.gad >= 0) and (result.gbd <= 99);
换句话说,您无法使查询作为子查询工作,因为它不符合子查询的要求。
答案 1 :(得分:1)
您的子查询具有重复的名称。使用alias
来区分
SELECT * FROM
(
SELECT t0.id, t0.gad, t0.gbd, t0.mandant, t0.gbd Tmp, t1.year
FROM person t0 LEFT OUTER JOIN control t1 ON (t0.id = t1.id)
WHERE ((t0.id='1') or (t0.id='2'))
) result
WHERE (result.gad >= 0) and (result.gbd <= 99);
答案 2 :(得分:0)
您可以在从数据库中读取子查询后修改子查询,以按照其他人的建议分配别名。 或者,如果您可以依赖子查询始终具有相同顺序的相同列集,则可以在不修改子查询的情况下尝试此操作:
SELECT *
FROM
(SELECT
t0.id, t0.gad, t0.gbd, t0.mandant, t0.gbd, t1.year
FROM
person t0
LEFT OUTER JOIN
control t1 ON (t0.id = t1.id)
WHERE ((t0.id = '1') or (t0.id = '2'))) result (id, gad, gbd1, mandant, gbd2, year)
WHERE
(result.gad >= 0) and (result.gbd1 <= 99);