Sami Ullah
Sami Ullah

Reputation: 129

How to execute another query in a running query after a specific number of records using php?

I searched a lot but didn't found the exact result that I need. I have a project of question and blog website. There are two tables question_table and blog_table, now I want to execute both in two different queries and ORDER BY date on one page as newsfeed. I'm sorry if I didn't explain well.

Attached Image for detail description (result must like this)

enter image description here

My sql query "SELECT * FROM blog_table WHERE status=1 ORDER BY posted_date DESC" and same for question_table "SELECT * FROM question_table WHERE status=1 ORDER BY posted_date DESC"

Please help me to findout the exact result in the image bellow.

How can I run this query:

select posted_at,user_id,post_title,post_data from blog_table 
UNION 
select asked_at,user_id,question_title,question_slug from question_table 
order by date desc

Upvotes: 1

Views: 326

Answers (1)

Barmar
Barmar

Reputation: 780724

Your ORDER BY only applies to the question_table query, not the whole thing. You need to put the UNION in a subquery so you can order the entire result.

SELECT *
FROM (
    select posted_at AS date, user_id, post_title AS title, post_data AS content 
    from blog_table 
    UNION 
    select asked_at AS date, user_id, question_title AS title, question_slug AS content 
    from question_table
) AS x
order by date desc

Upvotes: 1

Related Questions