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

birdietorerik's avatar

Get one colum from other table

Hi!

Making a application in laravel/vue In the model, i have this query:

 $query = DB::table('gpstrackers')
        ->select('*')
        ->whereIn('gpstrackers.id', function($query) use ($from1, $to1) {
            $query->selectRaw('MAX(gpstrackers.id) as id')
                ->from('gpstrackers')
                ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                ->whereBetween('gpstrackers.regdate',[$from1,$to1])
                ->groupBy('gpstrackers.flight','gpstrackers.player_id_ref');
        });

This query working fine.

But how to get -> users.name to. Add user.name to -> select('*') ????

0 likes
30 replies
Nakov's avatar

You need to add the join on your first query:

 $query = DB::table('gpstrackers')
        ->select('*', 'users.name')
        ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
        ->whereIn('gpstrackers.id', function($query) use ($from1, $to1) {
            $query->selectRaw('MAX(gpstrackers.id) as id')
                ->from('gpstrackers')
                ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                ->whereBetween('gpstrackers.regdate',[$from1,$to1])
                ->groupBy('gpstrackers.flight','gpstrackers.player_id_ref');
        });
birdietorerik's avatar

@Nakov Hi! Dosent work :(

Gives me this error:

SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select *, `users`.`name` from `gpstrackers` inner join `users` on `gpstrackers`.`player_id_ref` = `users`.`id` where `gpstrackers`.`id` in (select MAX(gpstrackers.id) as id from `gpstrackers` inner join `users` on `gpstrackers`.`player_id_ref` = `users`.`id` where `gpstrackers`.`regdate` between 2021-10-26 00:01 and 2021-10-26 09:00 group by `gpstrackers`.`flight`, `gpstrackers`.`player_id_ref`) and `type` <> 2 and `type` <> 12) union (select * from `holesclub`) union (select * from `objectsclub`))",
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@birdietorerik You have a union.. Your original question mentions nothing about a union :)

To make a union, the two queries needs to have the exact same number of columns selected.

Cardinality violation: 1222 The used SELECT statements have a different number of columns

birdietorerik's avatar

@Sinnbeck Hi! Sorry, dident include the hole code Here it is:

$query = DB::table('gpstrackers')
        ->select('*', 'users.name')
        ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
        ->whereIn('gpstrackers.id', function($query) use ($from1, $to1) {
            $query->selectRaw('MAX(gpstrackers.id) as id')
                ->from('gpstrackers')
                ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                ->whereBetween('gpstrackers.regdate',[$from1,$to1])
                ->groupBy('gpstrackers.flight','gpstrackers.player_id_ref');
        });
        
        if($holenumber=='true'){       
            $query1 = DB::table('holesclub');
            $query->union($query1);
        }

        if($flagget=='true'){       
            $query2 = DB::table('flagpositions');
            $query->union($query2);
        }

        if($toilet=='true'){       
            $query3 = DB::table('objectsclub');
            $query->union($query3);
        }
        
        if($flagget=='false')
        {           
            $query->where('type', '<>', 2);
        } 

        if($judge=='false')
        {           
            $query->where('type', '<>', 3);
        } 

        if($toilet=='false')
        {           
            $query->where('type', '<>', 5);
        } 

        if($holenumber=='false')
        {           
            $query->where('type', '<>', 7);
        } 

        if($dl=='false')
        {           
            $query->where('type', '<>', 12);
        } 

        if($bm=='false')
        {           
            $query->where('type', '<>', 8);
        } 

        if($td=='false')
        {           
            $query->where('type', '<>', 9);
        } 

        if($tl=='false')
        {           
            $query->where('type', '<>', 10);
        } 

        if($range=='false')
        {           
            $query->where('type', '<>', 11);
        } 

        if($green=='false'){
            $query->where('colormarker', '<>', 1);
        }

        if($orange=='false'){
            $query->where('colormarker', '<>', 2);
        }

        if($red=='false'){
            $query->where('colormarker', '<>', 3);
        }
        
        $gpsdata = $query->get();

        return $gpsdata;

Sinnbeck's avatar

@birdietorerik Why are you trying to union here? Seems like something you could get in either a join, or seperate query? This will give you a mixed list of gpstrackers, clubholes, flagpositions and objectsclub ? These does not sound like they are the same? If you make an excel sheet, would these go in the same sheet underneath each other? Cause that is what you are doing with this query.

birdietorerik's avatar

@Sinnbeck Hi!

Table -> gpstrackers wil have player_id_ref set to user in users table Table -> holesclub is a copy of table ->gpstrackers, but here is player_id-ref not used Table -> flagpositions is a copy of table ->gpstrackers, but here is player_id-ref not used Table -> objectsclub is a copy of table ->gpstrackers, but here is player_id-ref not used

So when i include users.name from users table in the first query. Union must olso include users.name

Like:

if($holenumber=='true'){       
            $query1 = DB::table('holesclub')
            ->select('*', 'users.name')
            ->join('users', 'holesclub.player_id_ref', '=', 0)
            $query->union($query1);
        }

This is why i cant use join on table -> holesclub, flagpositions and objectsclub

I can seperate this in 4 querys, but then code execute slower

Sinnbeck's avatar

@birdietorerik Ok if they are the same type, then its fine. Just didnt sound like it :) Then yes, just be sure to add the column to them all, so the column could is the same.

birdietorerik's avatar

Hi All!

Have this working code now, but give me a warning in the console

 $query = DB::table('gpstrackers')
        ->select('*', 'users.name')
        ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
        ->whereIn('gpstrackers.id', function($query) use ($from1, $to1) {
            $query->selectRaw('MAX(gpstrackers.id) as id')
                ->from('gpstrackers')
                ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                ->whereBetween('gpstrackers.regdate',[$from1,$to1])
                ->groupBy('gpstrackers.flight','gpstrackers.player_id_ref');
        });
        
        if($holenumber=='true'){       
            $query1 = DB::table('holesclub')
            ->select('*', 'users.name')
            ->join('users', 'users.id', '=','holesclub.player_id_ref');
            $query->union($query1);
        }

        if($flagget=='true'){       
            $query2 = DB::table('flagpositions')
            ->select('*', 'users.name')
            ->join('users', 'users.id', '=','flagpositions.player_id_ref');
            $query->union($query2);
        }

        if($toilet=='true'){       
            $query3 = DB::table('objectsclub')
            ->select('*', 'users.name')
            ->join('users', 'users.id', '=','objectsclub.player_id_ref');
            $query->union($query3);
        }
        
        if($flagget=='false')
        {           
            $query->where('type', '<>', 2);
        } 

        if($judge=='false')
        {           
            $query->where('type', '<>', 3);
        } 

        if($toilet=='false')
        {           
            $query->where('type', '<>', 5);
        } 

        if($holenumber=='false')
        {           
            $query->where('type', '<>', 7);
        } 

        if($dl=='false')
        {           
            $query->where('type', '<>', 12);
        } 

        if($bm=='false')
        {           
            $query->where('type', '<>', 8);
        } 

        if($td=='false')
        {           
            $query->where('type', '<>', 9);
        } 

        if($tl=='false')
        {           
            $query->where('type', '<>', 10);
        } 

        if($range=='false')
        {           
            $query->where('type', '<>', 11);
        } 

        if($green=='false'){
            $query->where('colormarker', '<>', 1);
        }

        if($orange=='false'){
            $query->where('colormarker', '<>', 2);
        }

        if($red=='false'){
            $query->where('colormarker', '<>', 3);
        }
        
        $gpsdata = $query->get();

        return $gpsdata;

Warnig message console:

[Vue warn]: Duplicate keys detected: '1'. This may cause an update error.
found in...
Sinnbeck's avatar

@birdietorerik This is because you are probably using the ID column as key.. You will have duplicate keys, as id =1 will exist in all tables etc :)

Sinnbeck's avatar

@birdietorerik I assume there is some other key on each table that makes it unique? Perhaps you can concatenate those

item.id + item.type
birdietorerik's avatar

@Sinnbeck Hi! only colum that is unique is id But how about somthing like a dummy = name

->select('*', 'ABC' as name) ???

But cant figer out what the right way to write this

birdietorerik's avatar

@Sinnbeck Hi!

But it dosent like this

 $query1 = DB::table('holesclub')
            ->select('*', 'dummy' as name);
            $query->union($query1);

Strange...

Sinnbeck's avatar

@birdietorerik Remember that we cannot guess the error :) What doesnt work? How doesnt it work? Perhaps create a new thread with this new specific issue

birdietorerik's avatar

@Sinnbeck Hi!

In the editor -> select..... have a red line under it

Error:

syntax error, unexpected 'as' (T_AS), expecting ',' or ')'
birdietorerik's avatar

@Sinnbeck Hi!

Sorry, gives me this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '"dummy"' in 'field list' (SQL: (select *, `users`.`name` from `gpstrackers` inner join `users` on `gpstrackers`.`player_id_ref` = `users`.`id` where `gpstrackers`.`id` in (select MAX(gpstrackers.id) as id from `gpstrackers` inner join `users` on `gpstrackers`.`player_id_ref` = `users`.`id` where `gpstrackers`.`regdate` between 2021-10-26 00:01 and 2021-10-26 09:00 group by `gpstrackers`.`flight`, `gpstrackers`.`player_id_ref`) and `type` <> 2 and `type` <> 12) union (select *, `"dummy"` as `name` from `holesclub`))",
Sinnbeck's avatar

@birdietorerik might need to be single quotes

$query1 = DB::table('holesclub')
            ->select('*', '\'dummy\' as name');  
birdietorerik's avatar

@Sinnbeck Hi!

Sorry:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column ''dummy'' in 'field list' (SQL: (select *, `users`.`name` from `gpstrackers` inner join `users` on `gpstrackers`.`player_id_ref` = `users`.`id` where `gpstrackers`.`id` in (select MAX(gpstrackers.id) as id from `gpstrackers` inner join `users` on `gpstrackers`.`player_id_ref` = `users`.`id` where `gpstrackers`.`regdate` between 2021-10-26 00:01 and 2021-10-26 09:00 group by `gpstrackers`.`flight`, `gpstrackers`.`player_id_ref`) and `type` <> 2 and `type` <> 12) union (select *, `'dummy'` as `name` from `holesclub`))",
"exception": "Illuminate\Database\QueryException",
Sinnbeck's avatar

@birdietorerik Ok I actually tried it out...

$query1 = DB::table('holesclub')
            ->select('*', DB::raw('"dummy" as name'));  
birdietorerik's avatar

@Sinnbeck Strange, i get this error:

"SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select *, `users`.`name` from `gpstrackers` inner join `users` on `gpstrackers`.`player_id_ref` = `users`.`id` where `gpstrackers`.`id` in (select MAX(gpstrackers.id) as id from `gpstrackers` inner join `users` on `gpstrackers`.`player_id_ref` = `users`.`id` where `gpstrackers`.`regdate` between 2021-10-26 00:01 and 2021-10-26 09:00 group by `gpstrackers`.`flight`, `gpstrackers`.`player_id_ref`) and `type` <> 2 and `type` <> 12) union (select *, "dummy" as name from `holesclub`))",
Sinnbeck's avatar

@birdietorerik I think we are back to the start again :). You need to add it to ALL the queries so the column count is identical.

birdietorerik's avatar

@Sinnbeck No, have this now

query = DB::table('gpstrackers')
        ->select('*', 'users.name')
        ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
        ->whereIn('gpstrackers.id', function($query) use ($from1, $to1) {
            $query->selectRaw('MAX(gpstrackers.id) as id')
                ->from('gpstrackers')
                ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                ->whereBetween('gpstrackers.regdate',[$from1,$to1])
                ->groupBy('gpstrackers.flight','gpstrackers.player_id_ref');
        });
        
        if($holenumber=='true'){       
            $query1 = DB::table('holesclub')
            ->select('*', DB::raw('"dummy" as name'));      
            $query->union($query1);
        }

So it has the same colums from 1 query and the last (with union)

Sinnbeck's avatar

@birdietorerik And you added it to the two last also? I cannot see why you are getting the error, but the error is clear.. Column count isnt the same.

birdietorerik's avatar

@Sinnbeck Hi! Have disabled the two other unions queryes When i get 1 first to work, i get other to to work.

Very very strange.

If i remove query 2 (with union) its working fine

Tray2's avatar

@birdietorerik it's not strange at all, its the way SQL works.

You have three parts of the query (Simplified example)

-- Part 0ne
SELECT col1, col2, col3
FROM table1
-- End Part One
UNION ALL
--Part Two
SELECT col1, col2
FROM table2
--End Part Two
UNION ALL
--Part Three
SELECT col1, col2, col3
FROM table3
--End Part Thee

The query above will fail with the same kind of error you got. That is because the first part of the query tells the database that you need three columns. Then it expects that the second and third part of the query also have three columns. The solution is to add that third column to part two. If the table for some reason doen't have three columns you need to fake it by adding a null column in your query.

-- Part 0ne
SELECT col1, col2, col3
FROM table1
-- End Part One
UNION ALL
--Part Two
SELECT col1, col2, null -- Fake null column added here
FROM table2
--End Part Two
UNION ALL
--Part Three
SELECT col1, col2, col3
FROM table3
--End Part Thee
birdietorerik's avatar

Hi!

I just tested this code:

 $query = DB::table('holesclub')
        ->select(DB::raw('*','"dummy" as name'));   

$gpsdata = $query->get();

No errors, but dosent add name colum ???

birdietorerik's avatar

Hi All!

Finaly i figer out the problem.

The first query :

$query = DB::table('gpstrackers')
        ->select('*', 'users.name')
        ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
        ->whereIn('gpstrackers.id', function($query) use ($from1, $to1) {
            $query->selectRaw('MAX(gpstrackers.id) as id')
                ->from('gpstrackers')
                ->join('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                ->whereBetween('gpstrackers.regdate',[$from1,$to1])
                ->groupBy('gpstrackers.flight','gpstrackers.player_id_ref');
        });

This query wil return all colums from users, not only users.name

Thats why seqond query dosent work, 2 query has no join

Must use left join (1 query) insted, like this:

 $query = DB::table('gpstrackers')
        ->select('gpstrackers.*', 'users.name')
        ->leftJoin('users', 'gpstrackers.player_id_ref', '=', 'users.id')
        ->whereIn('gpstrackers.id', function($query) use ($from1, $to1) {
            $query->selectRaw('MAX(gpstrackers.id) as id')
                ->from('gpstrackers')
                ->leftJoin('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                ->whereBetween('gpstrackers.regdate',[$from1,$to1])
                ->groupBy('gpstrackers.flight','gpstrackers.player_id_ref');
        });

Now its working fine :)

Thaank you all for help

Please or to participate in this conversation.