我在MySQL中有一个名为wp_usermeta的表: (这是一个wordpress应用程序,但我不想通过wordpress与数据库交互,只能通过MySQL)
umeta_id user_id meta_key meta_value
-------------------------------------------------------
1 1 nickname Rymdblomma
2 1 firstname Nile
3 1 lastname White
4 1 description Coolest person
等等。我想要的是选择所有这4个,而是放入4列。同时,我从其他表中选择数据,创建一个包含所有属性的临时表。
SELECT wp_users.ID AS wp_id,
wp_users.user_email AS email,
wp_users.user_login AS username,
wp_users.user_registered AS regDate,
wp_blogs.path AS subname,
wp_usermeta.meta_value AS firstname,
wp_usermeta.meta_value AS lastname
FROM wp_users
INNER JOIN wp_blogs ON wp_users.ID = wp_blogs.blog_id
LEFT JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id AND
(wp_usermeta.umeta_id = 2 OR wp_usermeta.umeta_id = 3);
(我想要包含所有meta_values,不仅仅是第一个和最后一个名字,但为了测试目的,我将其限制为2个)
返回如下内容:
wp_id email username regDate subname firstname lastname
-------------------------------------------------------------------------
1 blabla blabla blabla blabla Nile Nile
1 blabla blabla blabla blabla White White
等等。但我不想要重复的行,而是我想要这样的东西:
wp_id email username regDate subname firstname lastname
-------------------------------------------------------------------------
1 blabla blabla blabla blabla Nile White
我试图到处寻找任何帮助,但还没有找到任何帮助。任何帮助,将不胜感激。
答案 0 :(得分:2)
一种方法使用条件聚合:
SELECT u.ID AS wp_id, u.user_email AS email, u.user_login AS username,
u.user_registered AS regDate,
b.path AS subname,
MAX(CASE WHEN um.umeta_id = 2 THEN um.meta_value END) as firstname,
MAX(CASE WHEN um.umeta_id = 3 THEN um.meta_value END) as lastname
FROM wp_users u INNER JOIN
wp_blogs b
ON u.ID = b.blog_id LEFT JOIN
wp_usermeta umf
ON u.ID = um.user_id AND
um.umeta_id IN (2, 3)
GROUP BY u.ID, u.user_email, u.user_login,
u.user_registered, b.path;
答案 1 :(得分:1)
要将wp_usermeta中的名字和姓氏合并为一行,只需使用不同的umeta_id = join条件将表连接两次
SELECT wp_users.ID AS wp_id,
wp_users.user_email AS email,
wp_users.user_login AS username,
wp_users.user_registered AS regDate,
wp_blogs.path AS subname,
metafirstname.meta_value AS firstname,
metalastname.meta_value AS lastname
FROM wp_users
INNER JOIN wp_blogs ON wp_users.ID = wp_blogs.blog_id
LEFT JOIN wp_usermeta metafirstname ON wp_users.ID = metafirstname.user_id AND metafirstname.umeta_id = 2
LEFT JOIN wp_usermeta metalastname ON wp_users.ID = metalastname.user_id AND metalastname.umeta_id = 3;