我正在编写一个小应用程序,根据教师的查询标记学生在 PostgreSQL 中的查询。对于普通查询,我可以轻松地使用 EXCEPT 和 UNION 来查找不匹配项。但是我怎样才能检查那些需要排序的。
如果答案匹配所有行,但只有部分答案顺序正确。如何找到已排序的行数并正确标记大小写?
我的程序是使用 Psycopg2 库用 Python 编写的。
最佳答案
您可以比较由 row_number()
连接的两个查询。示例:
create table example (id int, str text);
insert into example values (1, 'alfa'), (2, 'beta');
with teacher as ( -- teachers query
select * from example order by id
),
student as ( -- students query
select * from example order by id desc
),
teacher_rn as (
select row_number() over () rn, *
from teacher
),
student_rn as (
select row_number() over () rn, *
from student
)
select t.*, s.*
from teacher_rn t
join student_rn s
on t.rn = s.rn
where t <> s;
rn | id | str | rn | id | str
----+----+------+----+----+------
1 | 1 | alfa | 1 | 2 | beta
2 | 2 | beta | 2 | 1 | alfa
(2 rows)
关于python - 比较 PostgreSQL 中具有 "ORDER BY"的 2 个查询的结果以检查匹配和不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33642843/