我有3张桌子
标签
UserValues
用户
标签看起来像这样:
1|First Name
2|Last Name
3|Favorite Book
etc...
用户看起来像这样:
1|[phone_number]
2|[phone_number]
etc....
UserValues看起来像这样:
1| [label_id_for_First_Name] |John | [user_id]
2| [label_id_for_Last_Name] |Smith | [user_id]
3| [label_id_for_Fav_Book] |Moby Dick | [user_id]
etc...
某些用户可能没有填写某些字段(除了用作主键的电话号码外,所有用户都是可选的)。
我很难过如何编写一个查询来压缩这些数据:
uid |First_Name|Last_Name | Favorite_Book
[user_id]|John |Smith | Moby Dick //user has all fields filled in
[user_id]|Mary | [null] | Kite Runner //user didn't have a last name
这个想法是,它的列宽会增加,因为有与这些特定用户相关联的标签。
我想选择用户,每个用户有1行,所有值都在右边。
我可以看到如何在多个查询中执行此操作,但我希望了解正确的方法是什么(也许是在多个查询中执行此操作,但我怀疑它不是这样)。
TIA。
答案 0 :(得分:1)
如果您想使用当前数据编写查询并在示例中给出结果,那就是:
SQL编码恐怖
SELECT
u.id as user_id
, uvfirstname.value as firstname
, uvlast_name.value as lastname
, uvbook.value as book
FROM users u
LEFT JOIN uservalues uvfirstname
ON (uvfirstname.label_id =
(SELECT l1.id FROM label l1 WHERE l1.name = 'First name')
AND uvfirstname.user_id = u.id)
LEFT JOIN uservalues uvlastname
ON (uvlastname.label_id =
(SELECT l2.id FROM label l2 WHERE l2.name = 'Last name')
AND uvlastname.user_id = u.id)
LEFT JOIN uservalues uvbook
ON (uvbook.label_id =
(SELECT l3.id FROM label l3 WHERE l3.name = 'Fav book')
AND uvbook.user_id = u.id)