简体   繁体   English

SQL比较行并在同一表的列中显示差异

[英]SQL compare rows with displaying differences in columns in the same table

Hello im looking for a query in SQL or MySQl about comparing rows in the same table 您好,我正在SQL中或MySQl中查找有关比较同一表中的行的查询

That query should display 2 last rows with the same id's but with different records in columns 该查询应显示最后2行,具有相同的ID,但列中的记录不同

My Table 我的桌子

ID|is_superuser|username|first_name|last_name|email          |is_staff|is_active|
 1|           1|admin   |FC        |         |admin@admin.com|       1|        1|
 1|           1|admin   |          |         |admin@admin.com|       1|        1|
 1|           1|admin   |adminname |         |admin@admin.eu |       1|        1|

RESULT : 结果:

ID|username|first_name|email|
 1|admin   |adminname |admin@admin.eu|
 1|admin   |          |admin@admin.com|

THX For Help THX寻求帮助

You could use an exists clause to demand that there is another row with the same id but a different email : 您可以使用一个exists子句要求另一行具有相同的id但不同的email

select  *
from    MyTable t1
where   exists
        (
        select  *
        from    MyTable t2
        where   t1.id = t2.id
                and coalesce(t1.email, '') <> coalesce(t2.email, '')
        )

Per your comment, if you have many columns, you can generate the where clause with a query like: 根据您的评论,如果您有许多列,则可以使用以下查询生成where子句:

select  concat('and coalesce(t1.', column_name, ', '''') <> coalesce(t2.', 
               column_name, ', '''')')
from    information_schema.columns
where   table_name = 'MyTable'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM