将多个mysql表结果聚合为一个

brgchamk  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(296)

我正在写一个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\ u value列同时包含了个人的位置和他们来自的国家。我需要我的html表显示每个人作为一个和显示国家,位置和姓名。

unhi4e5o

unhi4e5o1#

您可以使用组\u 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;
bf1o4zei

bf1o4zei2#

加入 wp_usermeta 两次,包括通缉犯 metakeyON 条款。

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;
5hcedyr0

5hcedyr03#

您可以使用聚合来获取每个实体及其不同属性的单行数据

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;

相关问题