在MySQL中,我有三个表格如下:
USERS:
USER_ID | USERNAME
1 | Homer Simpson
字段:
FIELD_ID | FIELD_NAME
1 | Phone
2 | Address
FIELD_VALUES:
USER_ID | FIELD_ID | FIELD_VALUE
1 | 1 | 555-1212
1 | 2 | 10 biteme drive
我想要做的是组合三个表,以便每个用户最终得到一行,字段名称为列标题和字段值,所以我最终得到:
USERS_TABLE:
USER_ID | USER_NAME | PHONE | ADDRESS
1 | Homer Simpson | 555-1212 | 10 biteme drive
答案 0 :(得分:2)
如果字段名称(电话和地址)已修复,您可以使用此技巧来转移数据:
SELECT
users.user_id,
users.user_name,
MAX(CASE WHEN field_id=1 THEN field_value END) AS Phone,
MAX(CASE WHEN field_id=2 THEN field_value END) AS Address
FROM
users INNER JOIN field_values
ON users.user_id = field_values.user_id
GROUP BY
users.user_id,
users.user_name
但如果您的值未修复,则需要使用动态查询:
SELECT
CONCAT(
'SELECT users.user_id,users.username,',
GROUP_CONCAT(CONCAT('MAX(CASE WHEN field_id=', field_id, ' THEN field_value END) AS `', field_name, '`')),
' FROM users INNER JOIN field_values ON users.user_id = field_values.user_id',
' GROUP BY users.user_id, users.username')
FROM `fields` INTO @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
请参阅小提琴here。
答案 1 :(得分:0)
尝试以下方法: -
SELECT
users.user_id,username, fv1.field_value value1, innertab.field_value value2
FROM
USERS LEFT JOIN FIELD_VALUES fv1
ON users.user_id = fv1.user_id
INNER JOIN FIELDS f1
ON fv1.FIELD_ID = f1.FIELD_ID AND f1.FIELD_ID = 1
LEFT JOIN
(SELECT
users.user_id, FIELD_VALUES.field_value
FROM
USERS LEFT JOIN FIELD_VALUES
ON users.user_id = FIELD_VALUES.user_id
INNER JOIN FIELDS
ON FIELD_VALUES.FIELD_ID = FIELDS.FIELD_ID AND FIELDS.FIELD_ID = 2) AS innertab ON
innertab.user_id = users.user_id