SQL select with with with multiple rows for one ID
SQL select with with multiple rows for one ID
我有两个表:
Table 1: 'user_fields'
id name
1 age
2 birthdate
3 firstname
Table 2: 'user_data'
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 语句来显示每个 user_id
的名字和生日
示例行:
22 Peter 01.01.1990
25 Steve 05.08.1970
select 应该是什么样子?
非常感谢!
您需要连接表(如果您不想对值进行硬编码),然后执行聚合:
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;
您可以尝试将 table 连接到自身并过滤仅连接名字和生日:
SELECT name.user_id, name.value AS Name, bday.value AS birthdate
FROM t name
INNER JOIN t bday
ON name.user_id = bday.user_id
AND name.t = 3 AND bday.t = 2
我有两个表:
Table 1: 'user_fields'
id name
1 age
2 birthdate
3 firstname
Table 2: 'user_data'
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 语句来显示每个 user_id
的名字和生日示例行:
22 Peter 01.01.1990
25 Steve 05.08.1970
select 应该是什么样子? 非常感谢!
您需要连接表(如果您不想对值进行硬编码),然后执行聚合:
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;
您可以尝试将 table 连接到自身并过滤仅连接名字和生日:
SELECT name.user_id, name.value AS Name, bday.value AS birthdate
FROM t name
INNER JOIN t bday
ON name.user_id = bday.user_id
AND name.t = 3 AND bday.t = 2