我有两张桌子:
表1:'用户字段'

id  name
1   age
2   birthdate
3   firstname

表2:'用户数据'
user_id user_field_id value
22          1           50
22          2           01.01.1990
22          3           Peter
25          1           33
25          2           05.08.1970
25          3           Steve

现在我想创建一个sql语句,它显示每个用户id的名字和生日
示例行:
22    Peter    01.01.1990
25    Steve    05.08.1970

选择应该是什么样子?
谢谢!

最佳答案

您需要联接表(如果不想硬编码值),然后执行聚合:

SELECT  ud.user_id,
        MIN(CASE WHEN uf.name = 'firstname' THEN ud.value END) as firstname,
        MIN(CASE WHEN uf.name = 'birthday' THEN ud.value END) as birthday
FROM user_data ud
INNER JOIN user_fields uf
    ON ud.user_field_id = uf.user_field_id
GROUP BY ud.user_id;

好的,根据你的新要求,一个简单的JOIN就可以了:
SELECT  ud.user_id,
        MIN(CASE WHEN uf.name = 'firstname' THEN ud.value END) as firstname,
        MIN(CASE WHEN uf.name = 'birthday' THEN ud.value END) as birthday,
        MIN(ac.status) as status
FROM user_data ud
INNER JOIN user_fields uf
    ON ud.user_field_id = uf.user_field_id
LEFT JOIN api_calls ac
    ON ud.user_id = ac.user_id
GROUP BY ud.user_id;

10-08 07:22