从主表中选择1行,从相关表

时间:2016-06-04 07:08:19

标签: php mysql relation

我有一个mysql"用户"表格:

id | name
1  | Jane Doe

和第二个表" custom_user_fields" (与userid相关):

id | userid | fieldname | value
1  | 1      | country   | us
2  | 1      | address   | test address

使用PHP,我必须创建一个包含所有用户及其相关字段的列表(如果可能只有一个查询)。

预期结果:

id | name     | country | address
1  | Jane Doe | us      | test address

可能吗?

1 个答案:

答案 0 :(得分:1)

对于表custom_user_fields中预定义的一组相关字段,这是可能的。您可以使用条件聚合

SELECT u.id, u.name,
       MAX(CASE WHEN fieldname = 'country' THEN value END) AS country, 
       MAX(CASE WHEN fieldname = 'address' THEN value END) AS address
FROM users AS u
LEFT JOIN custom_user_fields AS c ON u.id = c.userid 
GROUP BY u.id, u.name