我正在从 Sybase 迁移到 Netezza,但 Netezza 不支持此类查询。有人可以告诉我如何重写它吗?
UPDATE table1 t1
SET t1.col1=t2.col1
FROM table2 t2
WHERE t1.col2=t2.col2
AND t2.col3=(SELECT MAX(t3.col3) FROM table2 t3 WHERE t3.col2=t1.col2);
最佳答案
这种相关子查询实际上可以在 Netezza 中运行,具体取决于您的版本。
我碰巧运行的是 7.2,它运行得很好。
[nz@netezza ~]$ nzrev
Release 7.2.0.3 [Build 42210]
[nz@netezza ~]$ k^C
[nz@netezza ~]$ set -o vi
[nz@netezza ~]$ nzsql -d testdb
Welcome to nzsql, the IBM Netezza SQL interactive terminal.
Type: \h for help with SQL commands
\? for help on internal slash commands
\g or terminate with semicolon to execute query
\q to quit
TESTDB.ADMIN(ADMIN)=> UPDATE table1 t1
TESTDB.ADMIN(ADMIN)-> SET t1.col1=t2.col1
TESTDB.ADMIN(ADMIN)-> FROM table2 t2
TESTDB.ADMIN(ADMIN)-> WHERE t1.col2=t2.col2
TESTDB.ADMIN(ADMIN)-> AND t2.col3=(SELECT MAX(t3.col3) FROM table2 t3 WHERE t3.col2=t1.col2);
UPDATE 1
TESTDB.ADMIN(ADMIN)=>
不过,较新的版本(7.1 之前)无法处理该问题。以下是您如何将该特定情况重写为联接而不是相关子查询。
UPDATE table1 t1
SET t1.col1=t2.col1
FROM table2 t2,
(
SELECT col2,
MAX(col3) col3
FROM table2
GROUP BY col2
)
t3
WHERE t1.col2 = t2.col2
AND t2.col2 = t3.col2
AND t2.col3 = t3.col3;
documentation for v7.2.0关于相关子查询支持有这样的说法。
If you choose to use correlated subqueries, keep in mind the following restrictions on the form and placement of correlated subqueries:
You can use correlated subqueries in WHERE clauses.
You can use correlated subqueries in inner join conditions and with the equal join condition operator.
You can use correlated subqueries in mixed correlated expressions only in the following form:
expr(corr_columA, corr_columnB,...) = expr(local_columnX, local_columnY,...)
You cannot use correlated subqueries in SET operations (UNION, INTERSECT, EXCEPT, and MINUS).
You cannot use correlated subqueries in aggregates with GROUP BY and HAVING clauses.
You cannot use correlated subqueries in ORed clauses or in CASE/WHEN expressions.
You cannot use correlated subqueries in IN lists. You cannot use correlated subqueries in SELECT lists.
关于sybase - Netezza 相关查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28192472/