简体   繁体   中英

Laravel multiple sql select to AS

I'm trying to select multiple database columns and to merge them to an AS value statement like SELECT sum1 as vsd FROM tablename WHERE year = 2017

I have multiple columns I need to output as one value. So I imagine the above code looking something like this:

SELECT (sum1, sum2) as vsd FROM tablename WHERE year = 2017

My current live-code query looks like this:

$query = DB::table('exports')->select('id', 'year', 'week', 'month', 'staff_a, staff_b as vsd')->having('year','=',$year)->where('week', '<=', $weeknr)->orderBy('id', 'desc')->take(14)->get()->reverse();

The result is:

Column not found: 1054 Unknown column 'staff_a, staff_b' in 'field list'

I tried to combine them (columns) to an array ( array('staff_a', 'staff_b') ), had some weird foreach-loops and whatnot trying to make it work another way but all that threw yet another error message.

Is there any way to "merge" multiple selects to one?

You have to use RAW syntax:

->select(DB::raw('staff_a + staff_b as vsd'))

Ref: https://laravel.com/docs/5.5/queries#raw-expressions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM