1

我正在使用 Wordpress 和 Event Espresso,但一般来说,我有以下 SQL:

SELECT m.user_id, m.meta_key, m.meta_value from wp_usermeta as m
WHERE m.meta_key in ('event_espresso_city','event_espresso_state')
ORDER BY m.user_id

我正在尝试获取用户的城市和州,所以我想按 user_id 分组,但如果我这样做,它只会获取城市值并忽略或覆盖状态值。

有没有办法可以在('event_espresso_city','event_espresso_state')中执行 concat(m.metavalue1, m.meta_value2) WHERE m.meta_key?也就是说,它必须连接两行......有什么建议吗?

4

3 回答 3

3

MySQLGROUP_CONCAT()为此提供了功能。

在一般情况下,您必须将表与自身连接以从同一个表中的多个记录生成单个记录,例如:

SELECT m_city.user_id, m_city.meta_value as city, m_state.meta_value as state
FROM wp_usermeta as m_city
INNER JOIN wp_usermeta as m_state on m_city.user_id = m_state.user_id
WHERE m_city.meta_key = 'event_espresso_city'
AND m_state.meta_key = 'event_espresso_state'
ORDER BY m_city.user_id
于 2013-03-20T16:53:32.397 回答
2

尝试

Select coalesce(c.userId, s.userId) UserId, 
     c.meta_value City, s.meta_Value state
From wp_usermeta c
   full Join wp_usermeta s
       On s.UserId = c.UserId
          and c.meta_key = 'event_espresso_city'
          and s.meta_key = 'event_espresso_state'
Where @userId in (c.User_Id, s.User_id)
于 2013-03-20T16:54:19.420 回答
1

请参阅我对您的问题的评论,该帖子显示了使用自内连接来实现此目的的示例。您的查询将类似于:

SELECT ma.user_id, ma.meta_key as City, mb.meta_value as State
FROM wp_usermeta as ma
INNER JOIN wp_usermeta as mb
ON ma.user_id = mb.user_id
WHERE 
ma.meta_key = 'event_espresso_city'
AND
mb.meta_key = 'event_espresso_state'
ORDER BY ma.user_id
于 2013-03-20T16:55:35.560 回答