Selecting data from 3 tables with limit
Question
I have 3 tables ppc_offers, survery_offers,find_offers ( from admin section, i enter data into these tables)
Now on front end, i want to display latest 3 offers from these tables.
i.e. latest 3 will come, they can be from single table or multiple tables... it just has condition "latest 3"
How can i do this?
Laravel provides any way to do this?
or do i need to have any master table?
or can you suggest me regular SQL query for this?
Please help. Thanks.
PPC Table:
-------------------------
id | integer
title | varchar
url | varchar
description | varchar
created_at | timestamp
updated_at | timestamp
--------------------------
survey Table:
-------------------------
id | integer
title | varchar
created_at | timestamp
updated_at | timestamp
--------------------------
find code Table:
-------------------------
id | integer
title | varchar
url | varchar
description | varchar
code | varchar
created_at | timestamp
updated_at | timestamp
--------------------------
Solution
As a recommendation, it might make more sense to include all 3 of these offers in one table, and use an "offer_type" id to distinguish them from each other, instead of using 3 different tables. It might simplify your code.
I believe this may work with your current setup:
$ppc = DB::table('ppc_offers')
->select('title', 'url', 'description', 'NULL as code', 'updated_at');
$survey = DB::table('survey_offers')
->select('title', 'NULL as url', 'NULL as description', 'NULL as code', 'updated_at');
$find = DB::table('find_offers')
->select('title', 'url', 'description', 'code', 'updated_at');
return $ppc->unionAll($survey)->unionAll($find)
->orderBy('updated_at', 'desc')
->take(3)
->get();
OTHER TIPS
Make 3 queries union them with the same names for columns
select * from
(
(query1 order by id desc limit 3) x
union
(query2 order by id desc limit 3) y
union
(query3 order by id desc limit 3) z
(