Skip to content
Advertisement

MYSQL: UNION results between two tables where omitting records from first table if PK found in second table

I have two tables products and product_edits which hold product information on the pricelist. My app works in a way that if user changes any product info in products table it inserts it into product_edits table…

PRODUCTS table

PRODUCT_EDITS table

In above case I would like an SQL that returns records from both tables, but if product is found in product_edits table it selects only from product_edits and not also from products table.

I tried using standrd union but selects all records from both tables:

Advertisement

Answer

It’s better to use EXISTS instead of IN, in this case. You want the search to stop once you found a match, not go over all of the results from product_edits.

So do it like this:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement