一种方法是使用相关子查询将每个字段值作为列返回,
SELECT t.id
, (SELECT f1.value FROM mytable f1
WHERE f1.id = t.id AND f1.field_name = 'sign_up'
ORDER BY f1.value LIMIT 1
) AS SIGN_UP
, (SELECT f2.value FROM mytable f2
WHERE f2.id = t.id AND f2.field_name = 'first_name'
ORDER BY f2.value LIMIT 1
) AS FIRST_NAME
, (SELECT f3.value FROM mytable f3
WHERE f3.id = t.id AND f3.field_name = 'street'
ORDER BY f3.value LIMIT 1
) AS STREET
FROM (SELECT s.id
FROM mytable s
GROUP BY s.id
ORDER BY s.id
) t
这不是唯一的方法,但它是一种可行的方法,特别是如果您担心您将得到恰好返回的四列,并且它们将以特定的顺序返回。
请注意,当特定 ID“缺少”特定字段名称时,此方法有效(它将返回 NULL 代替值)。如果特定 ID 多次出现相同的 field_name,它也可以工作。(此查询将只返回其中一个,而忽略另一个。)
同样的结果集也可以通过这样的查询获得:
SELECT t.id AS ID
, f1.sign_up AS SIGN_UP
, f2.first_name AS FIRST_NAME
, f3.street AS STREET
FROM (SELECT s.id
FROM mytable s
GROUP BY s.id
ORDER BY s.id
) t
LEFT
JOIN (SELECT s1.id
, MIN(s1.value) AS sign_up
FROM mytable s1
WHERE s1.field_name = 'sign_up'
AND s1.value IS NOT NULL
GROUP BY s1.id
) f1
ON f1.id = t.id
LEFT
JOIN (SELECT s2.id
, MIN(s2.value) AS first_name
FROM mytable s2
WHERE s2.field_name = 'first_name'
AND s2.value IS NOT NULL
GROUP BY s2.id
) f2
ON f2.id = t.id
LEFT
JOIN (SELECT s3.id
, MIN(s3.value) AS street
FROM mytable s3
WHERE s3.field_name = 'street'
AND s3.value IS NOT NULL
GROUP BY s3.id
) f3
ON f3.id = t.id
对于其他查询,请确保在field_name
给定 ID“缺少”a、给定 ID 有重复项field_name
或表中存在您不关心的其他 field_name 值时获得所需的行为。