Search code examples
sqloracle-databaseplsqlsubqueryinner-join

oracle sql statement help to query against multiple tables


I am struggling with a sql statement. I am hoping a guru can help a beginner out, currently I have multiple select in statements.. but think there is a better way as I have been stuck.

Below are the tables and pertinent columns in each table

country
 -country_id
barcodes_banned_in_country
 -barcode(varchar)
 -country_id
 -country_name
orders
 -order_id
 -country_name
item
  -order_id
  -item_id
  -barcode(varchar)

The goal is to get all orders that are banned based off the barcode banned list. Any help with this sql statement would be appreciated.


Solution

  • One option uses exists:

    select o.*
    from orders o
    where exists (
        select 1
        from barcodes_banned_in_country bic
        inner join item i on i.barcode = bic.barcode
        where i.order_id = o.order_id and bic.country_name = o.country_name
    )
    

    This brings all orders whose at least one item have a barcode that is banned in the order's country.

    If, on the other hand, you want the list of the banned barcodes per order, then you can join and aggregate:

    select o.order_id, o.country_name, listagg(i.barcode, ',') banned_barcodes
    from orders o
    inner join item i 
        on  i.order_id = o.order_id
    inner join barcodes_banned_in_country bic 
        on  i.barcode = bic.barcode 
        and bic.country_name = o.country_name
    group by o.order_id, o.country_name
    

    Note that, as commented by MT0, you should really be storing the id of the country in orders rather than the country name. Accordingly, you wouldn't need the country name in the banned barcodes table.