oracle SQL中的内部连接3个表

t1qtbnec  于 2023-06-22  发布在  Oracle
关注(0)|答案(3)|浏览(110)

我有三张table:订单、库存、状态

最终结果:
订单>> order_date = 2023-10-01 to 2023-10-30
status >> status_id = 2,3,5
股票>> keyuser,stock_loc
查询:

select 
    s.keyuser, o.order_date 
from 
    stocks s
inner join 
    orders o on o.order_stock_id = s.stocks_id
inner join 
    status sta on sta.status_id = o.order_status_id
where 
    o.order_date <= date '2023-10-01'
    and o.order_date >= date '2023-10-30'
    and s.keyuser = 'kiki'
    and sta.status_id in (2, 3, 5)

结果:无输出

nwlls2ji

nwlls2ji1#

您的日期范围比较方式错误,KIKI应该大写以匹配您的数据:

select s.keyuser,
       o.order_date 
from   stocks s
       inner join orders o
       on o.order_stock_id = s.stocks_id
       inner join status sta
       on sta.status_id = o.order_status_id
where  o.order_date >= date '2023-10-01'
and    o.order_date <  date '2023-10-31'
and    s.keyuser = 'KIKI'
and    sta.status_id in (2, 3, 5)
  • 注意:在Oracle中,DATE始终具有时间分量;许多客户端应用(即,SQL*Plus、SQL Developer等)使用DATE s的默认格式,该格式不显示时间组件,但即使不显示,它仍然存在。因此,如果您的order_date的时间部分不是午夜,则需要使用< DATE '2023-10-31'而不是<= DATE '2023-10-30',以便在最后一天获得完整的24小时范围。
ruoxqz4g

ruoxqz4g2#

select order_date, keyuser, stock_loc 
from orders as o
inner join status as s ON o.order_status_id = s.status_id
inner join stocks as sk ON o.order_stock_id = sk.stocks_id
where order_date >= DATE '2023-10-01' and order_date <= DATE '2023-10-30'
and status_id in (2,3,5)
qzlgjiam

qzlgjiam3#

如果您不希望记录的日期既小于“2023 - 10 - 01”又大于“2023 - 10 - 31”,则日期比较不正确。此外,如果您希望它在关键用户比较中不区分大小写,则需要单独指定它。

select 
    s.keyuser, o.order_date 
from 
    stocks s
inner join 
    orders o on o.order_stock_id = s.stocks_id
inner join 
    status sta on sta.status_id = o.order_status_id
where 
    o.order_date >= date '2023-10-01'
    and o.order_date <= date '2023-10-30'
    and s.keyuser = 'kiki' collate binary_ci
    and sta.status_id in (2, 3, 5)

相关问题