我有一个显然是WordPress数据库的WordPress博客。
数据库名称:wordpress
通信的两个表格是wp_users
和wp_usermeta
。
表格usermeta
包含user_id
,meta_key
和meta_value
列。
user_id meta_key usermeta
1 name mark
1 userurl mark.com
1 points 8
2 name luke
2 userurl luke.com
2 points 4
2 name frank
2 userurl frank.com
2 points 6
我会在这样的特定页面上显示数据,并按点值desc:
排序Name: Mark
User Blog: mark.com
points: 8
Name: Frank
User Blog: mark.com
points: 6
Name: Luke
User Blog: luke.com
points: 4
我使用了这样的代码,但显然不会工作:
$sql =
"SELECT user_id, meta_key, meta_value" .
" FROM wp_usermeta" .
" WHERE meta_key IN ('name','userurl','points')" .
" ORDER BY meta_value DESC";
$usermeta = $wpdb->get_results($sql);
print("<ul>");
foreach ($usermeta as $post)
{
print('<li>' . $post->meta_value . '<br/>');
print('</li><br><br>');
}
print("</ul>");
答案 0 :(得分:1)
你可能会做类似
的事情select t1.user_id, t1.meta_value, t2.meta_value, t3.meta_value
from wp_usermeta t1
inner join wp_usermeta t2 on t1.user_id = t2.user_id and t2.meta_key = 'userurl'
inner join wp_usermeta t3 on t2.user_id = t3.user_id and t3.meta_key = 'points'
where t1.meta_key = 'name'
答案 1 :(得分:0)
试试这个
SELECT `user_id`,
max(case when `meta_key` = 'name' then `usermeta` end) as name ,
max(case when `meta_key` = 'userurl' then `usermeta` end) as website ,
max(case when `meta_key` = 'points' then `usermeta` end ) as points
FROM wp_usermeta
GROUP BY `user_id`
ORDER BY points DESC
您应该像这样构建表格,以便更好,更轻松地插入和更新并选择。
user_id name userurl points
1 mark mark.com 8
2 luke luke.com 4
3 frank frank.com 6
然后执行此查询
select * from table order by points
编辑:
$usermeta = $wpdb->get_results($sql) or die(mysql_error()) ;
echo"<ul>";
foreach ($usermeta as $post)
{
echo "<li>" . $post->name ." have ".$post->points. " Points </li><br /><br />" ;
}
echo "</ul>";
答案 2 :(得分:-1)
您是否考虑过使用2个查询?
第一个按点获取订单,第二个获取数据?然后操纵两个结果中的数据以创建一个新的有序数组?
SELECT user_id FROM wp_usermeta WHERE meta_key = 'points' ORDER BY meta_value DESC;
SELECT user_id, meta_key, meta_value WHERE meta_key IN ('name','userurl','points');