python - 比较 PostgreSQL 中具有 "ORDER BY"的 2 个查询的结果以检查匹配和不匹配

标签 python mysql postgresql sorting compare

我正在编写一个小应用程序,根据教师的查询标记学生在 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/

相关文章:

python - 使用 SQLAlchemy 将 pandas 数据帧导出到 MySQL

Python:根据列/行创建具有填充值的数组

php - 新手MySQL和php的问题

postgresql - Postgres查询错误

sql - 如何使用 SQL for 循环将行插入数据库?

sql - 在 Postgres 中解释解释分析的结果

python - 制作一个可停止的简单秒表

python - 如何将两列 csv 文件转换为 python 中的字典

javascript - 我将如何通过与另一个数组进行比较来更改 MySQL 数组?

python - 将列表添加到单个 MySQL 表字段中