【问题标题】:oracle sql statement help to query against multiple tablesoracle sql语句帮助查询多个表
【发布时间】:2021-02-09 06:25:15
【问题描述】:

我正在为一条 sql 语句而苦苦挣扎。我希望大师可以帮助初学者,目前我在语句中有多项选择..但我觉得有更好的方法,因为我被卡住了。

下面是表格和每个表格中的相关列

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)

目标是根据条形码禁止列表获取所有被禁止的订单。 对此 sql 语句的任何帮助将不胜感激。

【问题讨论】:

  • 为什么你有orders.country_name而不是country_id?为什么country_id不在country表中作为它的主键?
  • country_id 是 country 表中的主键,遗憾的是现在无法将 country_id 添加到 orders 表中。

标签: sql oracle plsql subquery inner-join


【解决方案1】:

一个选项使用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
)

这会将所有订单的至少一件商品的条形码在订单所在的国家/地区禁止。

另一方面,如果您想要每个订单的禁用条形码列表,那么您可以加入并聚合:

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

请注意,正如 MT0 所评论的那样,您确实应该将国家/地区的 id 存储在 orders 而不是国家/地区名称中。因此,您不需要禁止条形码表中的国家/地区名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多