我正在写一个有请愿书的wordpress网站,我需要按姓名,国家和地点向所有请愿者展示。
但是我使用的wordpress主题被设置为将请愿用户的值存储在多行中(似乎wordpress总是对用户这样做)。
每个用户都存储为具有“请愿者”角色的WordPress用户。我设法让所有请愿者使用此查询
SELECT display_name
, meta_value
, meta_key
FROM wp_users
JOIN wp_usermeta
ON wp_users.ID = wp_usermeta.user_id
WHERE meta_key = "petition_user_country"
OR meta_key = "petition_user_state"
AND meta_value !=""
ORDER
BY ID DESC;
此查询现在返回(仅包含测试数据)
+--------------------------+------------+-----------------------+
| display_name | meta_value | meta_key |
+--------------------------+------------+-----------------------+
| Test3 Test34 | AF | petition_user_country |
| Test3 Test34 | Tester | petition_user_state |
| Test Testnomsen | NO | petition_user_country |
| Test Testnomsen | Student | petition_user_state |
| Brushan | NO | petition_user_country |
| Kristian | Student | petition_user_state |
| Andreas Noe | NO | petition_user_country |
| Georg Simone | NO | petition_user_country |
+--------------------------+------------+-----------------------+
meta_value列包含人员的位置和他们所在的国家/地区。我需要我的HTML表格将每个人显示为一个并显示国家,位置和名称。
答案 0 :(得分:1)
加入wp_usermeta
两次,并在metakey
子句中加入所需的ON
。
SELECT display_name
, wpumc.meta_value country
, wpums.meta_value state
FROM wp_users
JOIN wp_usermeta wpumc
ON wp_users.ID = wpumc.user_id
AND wpumc.metakey = 'petition_user_country'
JOIN wp_usermeta wpums
ON wp_users.ID = wpums.user_id
AND wpums.metakey = 'petition_user_state'
WHERE wpumc.meta_value !=""
AND wpums.meta_value !=""
ORDER
BY ID DESC;
答案 1 :(得分:1)
您可以使用GROUP_CONCAT():
SELECT display_name, GROUP_CONCAT(meta_value) AS meta_value,
GROUP_CONCAT(meta_key) AS meta_value
FROM wp_users uw INNER JOIN
wp_usermeta um
ON uw.ID = um.user_id
WHERE meta_key IN ("petition_user_country", "petition_user_state") AND
meta_value != ""
GROUP BY display_name
ORDER BY ID DESC;
答案 2 :(得分:1)
您可以使用聚合来获取每个实体及其不同属性的单行数据
SELECT display_name,
MAX(CASE WHEN meta_key = 'petition_user_country' THEN meta_value ELSE NULL END) country,
MAX(CASE WHEN meta_key = 'petition_user_state' THEN meta_value ELSE NULL END) state,
FROM wp_users
JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id
WHERE meta_key IN('petition_user_country','petition_user_state')
AND meta_value !=""
GROUP BY display_name
ORDER BY display_name ASC;