mysql在join语句中使用列别名

时间:2015-03-30 06:27:05

标签: mysql inner-join

我有这样的查询:

select
    a.user_id,
    max(IF(a.meta_key = 'address',a.meta_value, NULL)) AS Address,
    max(IF(a.meta_key = 'mobile', a.meta_value, NULL)) AS mobile,
    max(IF(a.meta_key = 'topics', a.meta_value, NULL)) AS topics,
    b.user_email,
    b.user_login,
    b.display_name
from wp_ntusermeta a
inner join wp_ntusers b ON a.user_id = b.ID
where a.user_id in (select user_id from wp_ntusermeta
                    where meta_value like '%editor%')
group by a.user_id

工作正常,我有这样的结果

user_id | Address | mobile | topics | user_email    | user_login | display_name
     1  | chennai | 999... | 4      | xx@domain.com | xxx        | xxxyyy

我还有另一个名为wp_nttopics的表格,列数为topic_id, topic_name。使用此表与现有查询的连接,使用topics_id从结果中替换topic_name

预期结果:

user_id | Address | mobile  | topics         | user_email    | user_login | display_name   
     1  | chennai | 999.... | **topic_name** | xx@domain.com | xxx        | xxxyyy

1 个答案:

答案 0 :(得分:0)

将您的整个查询加入主题表:

select user_id, address, mobile,
topic_name as topics,
user_email, user_login, display_name
from (select a.user_id,
   max(IF(a.meta_key = 'address',a.meta_value, NULL)) AS Address,
   max(IF(a.meta_key = 'mobile', a.meta_value, NULL)) AS mobile,
   max(IF(a.meta_key = 'topics', a.meta_value, NULL)) AS topic_id,
   b.user_email,
   b.user_login,
   b.display_name
   from wp_ntusermeta a
   inner join wp_ntusers b ON a.user_id = b.ID
   where a.user_id in (select user_id from wp_ntusermeta
                where meta_value like '%editor%')
   group by a.user_id) data
 join wp_nttopics t on t.topic_id = data.topic_id
相关问题