我想根据Wordpress中的自定义字段列出帖子。
这里我有9个帖子,有3个不同的元数值(中间,左上,左下),元键是"位置"
这里是帖子表
Wp_posts:
Post ID title Description 1 Post1 ----- 2 Post2 ----- 3 Post3 ----- 4 Post4 --- 5 Post5 ---- 6 Post6 -- 7 Post7 ---- 8 Post8 --- 9 Post9 ---- 10 Post10 ---
这是wp_postmeta表:
meta_id post_id Meta_key meta_value 1 1 position left Top 2 2 position Left Bottom 3 3 position Left Top 4 4 position Left Bottom 5 5 position Middle 6 6 position Left Bottom 7 7 position Left Top 8 8 position Left Bottom 9 9 position Left top 10 10 position Middle
现在我想根据位置排序(中间,左下,左上)获得一个列表
喜欢这个
post_id title meta_value met_key 5 Post5 Middle postion 2 Post2 Left Bottom postion 1 Post1 Left Top postion 10 Post10 Middle postion 4 Post4 Left Bottom postion 3 Post3 Left Top postion 6 Post6 Left Bottom postion 7 Post7 Left Top postion 8 Post8 Left Bottom postion 9 Post9 Left Top postion
我不是sql查询的专家。
答案 0 :(得分:0)
这应该这样做:
ORDER BY FIELD(meta_value,'Middle','Left Bottom','Left Top')
有关ORDER BY FIELD功能的更多信息:http://www.electrictoolbox.com/mysql-order-specific-field-values/
答案 1 :(得分:0)
SELECT post_id, title, meta_value, Meta_key
FROM (
SELECT post_id, meta_value, Meta_key,
@grp := IF(@pos = meta_value, @grp + 1,
IF(@pos := meta_value, 1, 1)) AS grp
FROM wp_postmeta
CROSS JOIN (SELECT @grp := 0, @pos := '') AS vars
WHERE Meta_key = "position"
ORDER BY meta_value) AS t
LEFT JOIN Wp_posts
ON t.post_id = Wp_posts.PostID
ORDER BY grp, FIELD(meta_value, 'Middle', 'Left Bottom', 'left Top')
<强> demo 强>