I am certain this is non-conventional, however I am trying to perform the following:
I have the following Table:
products_id, company_id, products_name
1, 1, shoes
1, 2, mens shoes
2, 1, pants
Now, what I want to do is select a particular products_name from this using a given products_id and company_id = ‘2’, however in all cases where it does not find a row with company_id = ‘2’ I want it to default to giving me the products_name for the same product_id with ANY company_id.
For instance, if I were to search for products_id = ‘2’, company_id = ‘2’ it should return products_name = ‘pants’. However, if I were to search products_id = ‘1’, company_id = ‘2’ it should return ‘mens shoes’. If I were to search products_id = ‘3’, company_id = anything – it should return an empty set.
I need to be able to do this in a single SQL statement, so no handling via PHP to confirm whether or not a row exists with say: products_id = ‘2’ company_id = ‘2’.
The actual application uses a far more complex table with multiple joins, however it’s this simple bit that I cannot figure out, so if anyone could help me with this hurdle it would be much appreciated.
Here is a query that will return the company’s product, or any generic one if there isn’t a specific product for that company, across the entire product list. It can easily be filtered with an extra
where products_id = ##at the end (or by putting awherefilter inside the two inner sub-queries which might actually be more efficient):Demo: http://sqlize.com/pkt568O0b5
The basic idea behind my logic was this:
maxof product name and grouping by id.NULL.maxof product name. This is handled through thecoalescefunction, which returns the first non-null argument in its list. So basically it checks the company-specific list first, and if nothing is available, uses the generic list instead.Hope this helps!