且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为相同ID的多行选择不同的值

更新时间:2023-10-25 15:38:04

您可以使用以下简单解决方案:

You can use this simple solution:

SELECT DISTINCT
    a.id,
    b.value AS SIGN_UP,
    c.value AS FIRST_NAME,
    d.value AS STREET
FROM tbl a
LEFT JOIN tbl b ON a.id = b.id AND b.field_name = 'sign_up'
LEFT JOIN tbl c ON a.id = c.id AND c.field_name = 'first_name'
LEFT JOIN tbl d ON a.id = d.id AND d.field_name = 'street'

为了安全起见,我进行了联接LEFT JOIN,因为我不知道id是否可以具有 missing 字段,在这种情况下,它们将在我们的字段中显示为NULL派生列.

Just to be safe, I made the joins LEFT JOIN's because I do not know if an id can have missing fields, in which case they will show up as NULL in our derived columns.

SQL小提琴演示