I have a table called post
which contains WordPress posts that have this structure:
ID post_title post_type 1 foo1 zoacres-property 2 foo2 zoacres-property 3 foo3 zoacres-property 4 foo4 post
each zoacres-property
post have a meta stored inside the meta
table:
meta_id post_id meta_key meta_value 100 1 price 5000 101 2 price 10000 102 3 price 0
I’m trying to filter the zoacres-property
post by price, and I successfully did this using this query:
SELECT * FROM post p LEFT JOIN meta m ON p.ID = m.post_id AND m.meta_key = 'price' AND p.post_type = 'zoacres-property' GROUP BY p.ID ORDER BY m.meta_value+0 LIMIT 0,6
which returns:
ID post_title post_type meta_id post_id meta_key meta_value 3 foo3 zoacres-property 102 3 price 0 1 foo1 zoacres-property 100 1 price 5000 2 foo2 zoacres-property 101 2 price 10000
this result is correct but, I would like to display all the property which have a price of 0
as first (as in the output), and after these, I need to display the property with a non 0 price using DESC
, so the correct ouput the I want is:
ID post_title post_type meta_id post_id meta_key meta_value 3 foo3 zoacres-property 102 3 price 0 2 foo2 zoacres-property 101 2 price 10000 1 foo1 zoacres-property 100 1 price 5000
As you can see the post with price 0
are the firsts displayed, and then I want get all the posts with the high price to lowest. Is possible achieve this?
I also created a FIDDLE HERE.
Advertisement
Answer
You can use conditional ordering as
SELECT * FROM post p JOIN meta m ON p.ID = m.post_id AND m.meta_key = 'price' AND p.post_type = 'zoacres-property' ORDER BY m.meta_value+0 = 0 desc, m.meta_value+0 desc LIMIT 0,6