如果我删除最后的JOIN行,这是有效的,但我不确定为什么它不能用它。 最后两个JOIN语句试图从同一个表中的不同行中获取数据('meta_value'),其名称只能通过读取同一个表中的另一个相应列('meta_key')来找到。所有这一切都加入了所有3个表中的user_id common上的所有内容。
SELECT mod_membership.uid,
mod_membership.wp_user_id,
mod_membership.status,
mod_membership.last_login,
mod_membership.membership_type,
mod_membership.membership_expiration,
wp_users.user_login,
wpm_a.meta_value AS first_name
FROM mod_membership
JOIN wp_users ON wp_users.ID = mod_membership.wp_user_id
JOIN wp_usermeta AS wpm_a ON wpm_a.user_id = mod_membership.wp_user_id WHERE wpm_a.meta_key = 'first_name'
JOIN wp_usermeta AS wpm_b ON wpm_b.user_id = mod_membership.wp_user_id WHERE wpm_b.meta_key = 'last_name'
如何让第三个JOIN工作,或者使用其他方法将这些结果集中在一个结果集中,并在user_id上分组?
答案 0 :(得分:4)
试试这个:
SELECT m.uid, m.wp_user_id,m.status,
m.last_login,m.membership_type,
m.membership_expiration,
u.user_login,
f.meta_value first_name,
l.meta_value last_name
From mod_membership m
Join wp_users u
On u.ID = m.wp_user_id
Left Join wp_usermeta f
On f.user_id = m.wp_user_id
And f.meta_key = 'first_name'
Left Join wp_usermeta l
On l.user_id = m.wp_user_id
And l.meta_key = 'last_name'
回答你的问题,你的语法不起作用的原因是,首先,每个sql语句只能有一个where子句。你不能为每个连接添加一个where子句,这就是“On”cluase的用途......
其次,在生成最终结果集之前,不应用Where子句中的条件,而在“沿途”评估连接条件,因为每个中间结果集都是从每个连续的连接语句构造的。
答案 1 :(得分:3)
据我所知,你不需要第3次加入 - 看起来你正试图这样做:
SELECT DISTINCT mod_membership.uid, mod_membership.wp_user_id,
mod_membership.status, mod_membership.last_login,
mod_membership.membership_type, mod_membership.membership_expiration,
wp_users.user_login, wpm_a.meta_value AS first_name
FROM mod_membership
INNER JOIN wp_users ON wp_users.ID = mod_membership.wp_user_id
INNER JOIN wp_usermeta AS wpm_a ON wpm_a.user_id = mod_membership.wp_user_id
WHERE (wpm_a.meta_key = 'first_name' OR wpm_a.meta_key = 'last_name')
原始查询不起作用的原因是您只能有一个WHERE子句。
答案 2 :(得分:1)
为AND
交换WHERESELECT mod_membership.uid,
mod_membership.wp_user_id,
mod_membership.status,
mod_membership.last_login,
mod_membership.membership_type,
mod_membership.membership_expiration,
wp_users.user_login,
wpm_a.meta_value AS first_name
FROM mod_membership
JOIN wp_users ON wp_users.ID = mod_membership.wp_user_id
JOIN wp_usermeta AS wpm_a ON wpm_a.user_id = mod_membership.wp_user_id AND wpm_a.meta_key = 'first_name'
JOIN wp_usermeta AS wpm_b ON wpm_b.user_id = mod_membership.wp_user_id AND wpm_b.meta_key = 'last_name'