这是来自Wordpress的查询,但以这种方式适用于任何数据库设置。它们有一些存储在元字段中的数据。有一个表有两个名为meta_name和meta_value的字段。这些字段用于存储几乎所有内容。例如,meta_name可以是“lastname”,meta_value是该名称的值。我有一个将返回所有用户的查询,但是当meta_name =“lastname”时,如何按meta_value排序?以下是当前查询。
SELECT um.user_id, users.display_name, GROUP_CONCAT(um.meta_value SEPARATOR ' ')
FROM `wp_7bv88z_usermeta` um, `wp_7bv88z_pmpro_memberships_users` u, `wp_7bv88z_users` users
WHERE u.user_id=um.user_id and users.ID=u.user_id and (um.meta_key='pmpro_sfirstname' or um.meta_key='pmpro_slastname')
and u.status='active'
GROUP BY um.user_id
示例数据:
user_meta表
╔════=====╦══════════════==╦══════=======╗
║ user_id ║ meta_key ║ meta_value ║
╠════=====╬══════════════==╬══════=======╣
║ 1 ║ pmpro_sfirstname ║ Jeff ║
║ 1 ║ pmpro_slasttname ║ Atwood ║
║ 2 ║ pmpro_sfirstname ║ Geoff ║
║ 2 ║ pmpro_slasttname ║ Davis ║
║ 3 ║ pmpro_sfirstname ║ Jarrod ║
║ 3 ║ pmpro_slasttname ║ Minor ║
║ 4 ║ pmpro_sfirstname ║ Joel ║
║ 4 ║ pmpro_slasttname ║ Brown ║
╚════=====╩════════════=====╩══════======╝
预期结果:
1, Jeff Atwood
4, Joel Brown
2, Geoff Davis
3, Jarrod Minor
答案 0 :(得分:2)
我不是旧语法或交叉联接的粉丝 - 但你可以做这样的事情;
SELECT um.user_id,
users.display_name,
GROUP_CONCAT(um.meta_value SEPARATOR ' ')
FROM `user_meta` um,
`memberships_users` u,
`users` users,
`user_meta` lname,
`user_meta` fname
WHERE u.user_id = um.user_id
and users.id = u.user_id
and (lname.user_id = u.user_id and lname.meta_key = 'pmpro_slastname')
and (fname.user_id = u.user_id and fname.meta_key = 'pmpro_sfirstname')
and (um.meta_key='pmpro_sfirstname' or um.meta_key='pmpro_slastname')
and u.status='active'
GROUP BY lname.meta_value, fname.meta_value, um.user_id
请参阅此SQLFiddle以查看其实际操作