php—如何将表1中的所有记录和表2中的元数据放在一起?

lkaoscv7  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(254)

我想知道是否有其他方法可以从表1(users)中获取所有记录,以及表2(user\u meta)中获取所有元数据,我现在使用的方法是:

SELECT 
u.id, 
u.username, 
u.email, 
r.role,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'sidebar_color' LIMIT 1) AS sidebar_color,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'profile_pic' LIMIT 1) AS profile_pic,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'thumbnail' LIMIT 1) AS thumbnail,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'bg_img' LIMIT 1) AS bg_img,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'bio' LIMIT 1) AS bio,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'google' LIMIT 1) AS google,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'facebook' LIMIT 1) AS facebook,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'twitter' LIMIT 1) AS twitter,
(SELECT val FROM user_meta WHERE id_parent = u.id AND attr = 'whatsapp' LIMIT 1) AS whatsapp
FROM users u 
LEFT JOIN roles r ON u.id_role = r.id
ORDER BY u.id
ASC

它是工作的,我从所有的用户那里得到所有的数据,但是我想换一种方法,因为我将使用同样的方法来进行crm,但是这个方法会有太多的元数据,而且它将是一个需要维护的巨大查询。
谢谢您。

hi3rlvi2

hi3rlvi21#

你的方法很好,在很多情况下都是最快的。但聚合也是可行的:

SELECT um.id_parent,
       MAX(CASE WHEN um.attr = 'sidebar_color' THEN val END) as sidebar_color,
       MAX(CASE WHEN um.attr = 'profile_pic' THEN val END) as profile_pic,
       . . .
FROM user_meta um
GROUP BY um.id_parent;

这通常是 FROM 条款。
对于获取所有用户的信息,这可能比 JOIN 方法,因为键的数量变大。但是,如果要筛选到一个或少数用户,则需要在聚合之前进行筛选以获得良好的性能。

相关问题