简体   繁体   中英

MySQL JOIN ON, if column x is not null otherwise column y

I would like to join my products table, while grabing the orders.

I have a orders.product_id, which always have a value.

But the case is, if orders.bproduct_id is not null, we should go by this product id instead at the

->join('products')->on('products.id', '=', 'dealsite_orders.product_id')

(I am using Kohana Query Builder, but I accept an query answer)

How would I do this?

When I do:

JOIN ON COALESCE(orders.bproduct_id,product_id)

It does not return any rows. After investigating I found out, its because it takes column value from bproduct_id even if its 0 ?

The on expression you are looking for something like this:

on products.id = coalesce(dealsite_orders.product_id, orders.product_id)

The coalesce() function returns the first value that is not null in the list of columns. I'm not sure if you want to use this on the dealsite column or the products column.

Note that the use of coalesce() may prevent the use of an index. If your tables are large, you might want to re-formulate the query to take advantage of your indexes.

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