简体   繁体   中英

Any way to force Mysql to use column from select in where clause when column is ambiguous?

I have query:

select products.* from products
join companies on companies.id = products.company_id
where id = 1;

query generates error "Column 'id' in where clause is ambiguous". I know that column is ambiguous, but I want tell mysql to look only columns in select "products. ". So if I have "products. " id from products will be examined in where clause, if I have "companies. " id from companies will be examined in where clause, if I have "products. , companies.*" only then id will be ambiguous.

This is just plain example, query is more complicated and generated by ORM. I know I can use

select products.id as products_id from products

and then use

where products_id  = 1

or I can use

where products.id = 1;

but this does not fit to my needs because query is generated by orm. Any ideas ?

You can specify from which table you want to use id as you wrote:

WHERE products.id = 1

When using eloquent you can do it in using DB::raw:

DB::table('products')
    ->select(DB::raw('products.*'))
    ->join('companies', DB::raw('companies.id'), '=', DB::raw('products.company_id'))
    ->where(DB::raw('products.id'), '=', 1)
    ->get()
;
select products.* from products
join companies on companies.id = products.company_id
where products.id = 1;

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