sql - Update a column in table only if a condition is met for number of values for a field in other table -


i trying figure out how achieve following. (this simplified version ignores/ stripped off non-relevant columns.)

i have table item columns

item_id   product 

i have table order columns

order_id product item_id 

here problem statement.

for given item_id in item table, find orders have 1 distinct product associated in order table.
mind you, one distinct product mean 1 or more rows unique combination of product , item_id. in case, need take product derived order table , update item table value.

so if order table has values

scenario i
order table

order_id product  item_id 1        apple        12 2        apple        12 

then need update product in item table "apple"

scenario ii
however, if order table has values

order_id product item_id 1        apple        12 2        orange       12 

nothing needs done. product in item table needs no update. (it null default.) . 1 time data fix. going forward relationship between order , item table handled application. in case, product in order table stays after conditional update item table.

what solution problem?

this seems requested:

update item_table set i.product =    (select     min(o.product)    order_table o    i.item_id = o.item_id    group o.item_id    having count(distinct o.product) = 1   ) i.product null ; 

see in action: sql fiddle.
please comment, if requires adjustment / further detail.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -