Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

_NinjaDev's avatar

Query Builder multiple sub queries

Any ideas how use query builder with this query?

SELECT * from 
	(SELECT * from table2) t1,
	(SELECT * from table2) t2,
	(SELECT * from table3) t3,
	(SELECT * from table4) t4
0 likes
7 replies
_NinjaDev's avatar

Crossjoin isn't the answer here. There is no base table. And don't mind the results. I'm about the query builder.

Most close answer to this is using DB::query()

Like this:

        $query = DB::query();

        $sql = $query->fromSub(function($q){
            $q->from('table1 as t1');
            $q->select('*');
        },'main')->toSql();

which translates to "select * from (select * from `table1` as `t1`) as `main`"

But the problem is on multiple fromSubs.

MichalOravec's avatar
$first = DB::table('first_table')->selectRaw('column_one AS one, column_two AS two');

$second = DB::table('second_table')->selectRaw('column_one AS one, column_two AS two');

// add more tables

$results = DB::table('third_table')->selectRaw('column_one AS one, column_two AS two')
    ->union($first)
    ->union($second)
   	// add more unions
    ->get();

https://laravel.com/docs/8.x/queries#unions

_NinjaDev's avatar

Your answer is very far from the question.

sr57's avatar

Hi @ninjadev

Your OP is an eloquent "crossjoin" that's a cartesian product with all the table that's why I alert you about the possible GIANT result (nr1 * nr2 * nr3 * nr4)

It's not a union query (nr1 + nr2 + nr3 +nr4)

Looking at your 2nd msg, that's different from your OP, I don't know if there is way like this but, if your OP is correct, use simply crossjoin https://laravel.com/docs/8.x/queries#cross-join-clause

You are right saying that with crossjoin there is no base table, but neither there is in your OP.

kima's avatar

AFAIK, although it's specified in the from clause and no JOIN clause is set, the query is actually handled as a join.

you can still achieve this by using fromRaw

DB::query()->fromRaw('((SELECT * from table2) t1,(SELECT * from table2) t2,(SELECT * from table3) t3,(SELECT * from table4) t4)')->select("*")->get()

Please or to participate in this conversation.