【问题标题】:Fetching data from multiple tables applying join using Oracle SQL使用 Oracle SQL 从应用连接的多个表中获取数据
【发布时间】:2021-11-16 17:41:33
【问题描述】:

我是 sql 查询的新手。我有从这 3 个表中获取数据的基本查询,下面是查询,

select t.transction_id,pt.name,pa.date from transaction t, position_acc pa,position_trans pt where 
t.transction_id=pt.transction_id and pt.postion_id=pa.postition_id

========================

现在我有一个要求,我必须从另一个表调用中获取数据,移动

这是我客户的条件。他们需要移动表中的所有数据,即使 position_trans 或 position_acc 中没有匹配的数据。

所以,这是我的客户的条件:

select t.transction_id ,m.movement_id from transction t,movement m where t.transction_id=m.movement_id and m.name="CASH"

如何将这种情况与我的基本查询结合使用。客户端需要来自移动的所有数据。如果匹配的列在 position_trans 或 position_acc 中没有条目,它们很好。他们将接受这些列中的列为空。

那么,我怎样才能将我的运动条件放入基本查询中。请帮助

======

select t.transction_id ,m.movement_id from transction t,movement m where t.transction_id=m.movement_id and m.name="CASH"

  Record count =1500.
The count should be same after appending with base query.

【问题讨论】:

  • 使用标准的 JOIN 语法。你想要 LEFT JOIN。
  • @Serg 在基本查询之后我应该在哪里使用左连接?从事务 t 中选择 t.transction_id,pt.name,pa.date, position_acc pa,position_trans pt where t.transction_id=pt。 transction_id 和 pt.postion_id=pa.postition_id LEFT 在 t.transction_id=m.movement_id 上加入运动 m,其中 m.name="CASH"。对吗??

标签: java sql oracle


【解决方案1】:

此查询返回所有处于事务和移动中的条目,它们必须具有连接,否则它们不会显示。 position_trans 和 position_acc 中的记录在该查询中是可选的:

select t.transction_id, pt.name, pa.date, m.movement_id 
from transaction t
inner join t.transction_id=m.movement_id
left join position_trans pt on t.transction_id=pt.transction_id
left join position_acc pa on pt.postion_id=pa.postition_id

如果您想要方法中的所有记录,无论它是否在事务中有相关记录,您都需要从方法中选择并左连接到事务,如下所示:

select t.transction_id, pt.name, pa.date, m.movement_id 
from method m
left join transaction t on m.movement_id = t.transction_id
left join position_trans pt on t.transction_id=pt.transction_id
left join position_acc pa on pt.postion_id=pa.postition_id

此时我想参考this

【讨论】:

    【解决方案2】:

    永远不要FROM 子句中使用逗号。 始终使用正确、明确、标准、可读的JOIN语法。

    在您的情况下,您似乎只是想要 LEFT JOINmovement

    select t.transction_id, pt.name, pa.date, m.movement_id
    from position_acc pa join
         position_trans pt
         on pt.postion_id = pa.postition_id join
         transaction t
         on t.transction_id = pt.transction_id left join
         movement m 
         on t.transction_id = m.movement_id and m.name = 'CASH'
         
    

    【讨论】:

    • 嗨@Gordon,如果我单独运行查询 select t.transction_id ,m.movement_id from transction t,movement m where t.transction_id=m.movement_id and m.name="CASH", the记录数为 1500。但在申请加入后,它是 3181。计数发生了变化
    • 也许你不需要使用left join 来对付运动,如果对于任何交易ID,你有运动ID。 @Gordon 解决方案应该可以工作,也许你的逻辑不准确。
    • @Roberto hernandez ..没有得到..不需要左连接意味着..我将如何连接它
    • 普通join,和其他人一样,然后你可以再次检查计数器
    • @Debo 。 . . movements 表中似乎有多个匹配项。
    猜你喜欢
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多