mysql query to get preview data

1.3k Views Asked by At

I have one table in which I have id and parent_id. In admin panel if user click on preview button it redirects to site with preview id. when we click on preview button, data save in table with it's id in 'parent_id' key.

I created query and its working fine but it's displaying data in order but i want to replace parent row with preview row.

select * from wp_content
where page='sharepoint_features'
and (status='1' or (status='preview' and parent_id='146'))
and id<>146

here 146 is parent id which we got form preview id

by this query we have got following data

enter

in above table id 1303 should come after 145

2

There are 2 best solutions below

3
On

Here is a possible work around based on @JoeTaras solution:

select * from wp_content
where page='sharepoint_features'
and (status='1'
    or (status='preview' and parent_id='146'))
and id<>146
order by coalesce(NULLIF(parent_id, ''), id)

Here is a sqlfiddle with what I assume is your data structure.

9
On

You must add an ORDER BY clause so,

Try this:

select * from wp_content
where page='sharepoint_features'
and (status='1'
    or (status='preview' and parent_id='146'))
and id<>146
order by coalesce(CAST(parent_id as INT), id)

UPDATE

Dear, this is the SqlFiddle, so if I understand your request, the result it's OK.

My result is:

144 - a - null
145 - b - null
1303 - c - 146
147 - d - null

UPDATE 2

Try with this query and tell if it's OK:

select * from wp_content
where page='sharepoint_features'
and (status='1'
    or (status='preview' and parent_id='146'))
and id<>146
order by 
case 
    when parent_id is null then id
    else CONVERT(cast parent_id as INT)
end