簡體   English   中英

SQL比較行並在同一表的列中顯示差異

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

您好,我正在SQL中或MySQl中查找有關比較同一表中的行的查詢

該查詢應顯示最后2行,具有相同的ID,但列中的記錄不同

我的桌子

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|

結果:

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

THX尋求幫助

您可以使用一個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, '')
        )

根據您的評論,如果您有許多列,則可以使用以下查詢生成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