【问题标题】:How to do a "selective where" in Oracle 10g?如何在 Oracle 10g 中进行“选择性位置”?
【发布时间】:2012-07-16 14:01:22
【问题描述】:

我有一个父表 A,它有 2 个外键(来自表 B 和 C),但它一次只能有一个外键。示例:

SELECT a.evi, a.time, a.date, 
       a.number, a.descr, a.x, 
       a.y, a.z,  a.FK_tableB, a.FK_tableC, 
       b.brand, b.type, 
       b.color, b.model, c.name, c.lastname, 
  FROM tableA a, 
       tableB b, 
       tableC c  
 WHERE (PK_tableA = 100 AND PK_tableB = FK_tableB)      
    OR (PK_tableA = 100 AND PK_tableC = FK_tableC)

(这显然行不通)

当只有一个 where 子句为真时,我如何返回数据。

【问题讨论】:

标签: sql oracle


【解决方案1】:

您似乎想对您的查询执行“异或”(XOR)。

由于 SQL 没有 XOR,您可以尝试以下操作:

create table a
( a_id int, b_id int, c_id int);

create table b
( b_id int);

create table c
( c_id int);

insert into a (a_id, b_id, c_id) values (1, 1, 1);
insert into a (a_id, b_id, c_id) values (2, NULL, 2);
insert into a (a_id, b_id, c_id) values (3, 2, NULL);
insert into a (a_id, b_id, c_id) values (4, NULL, NULL);

insert into b (b_id) values (1);
insert into b (b_id) values (2);

insert into c (c_id) values (1);
insert into c (c_id) values (2);

SELECT a.a_id, a.b_id, a.c_id, b.b_id, c.c_id
  FROM a 
  LEFT JOIN b
    ON (a.b_id = b.b_id)
  LEFT JOIN c  
    ON (a.c_id = c.c_id)
 WHERE (   (b.b_id is NOT NULL AND c.c_id is NULL) 
        OR (c.c_id is NOT NULL AND b.b_id is NULL));

查看此SQLFiddle 进行尝试。

【讨论】:

  • 这是迄今为止唯一匹配问题的解决方案
  • 请注意,我不容忍这种桌子设计——它有点令人困惑。如果您真的可以拥有一把钥匙但不能拥有另一把钥匙,那么您可能需要重新设计表格中的两把钥匙。
  • 谢谢,这正是我所需要的。对不起这个蹩脚的例子,我在一个开发者的街区,每条评论都非常有用。感谢您的宝贵时间。你们摇滚=)
【解决方案2】:

使用希望使用左外连接来保留表 A 中的所有行,即使其他表中没有匹配的行。

SELECT a.evi, a.time, a.date, a.number, a.descr, a.x, a.y, a.z,  a.FK_tableB,
       a.FK_tableC, b.brand, b.type,  b.color, b.model, c.name, c.lastname
FROM tableA a left outer join
     tableB b
     on a.FK_TableB = b.PK_tableB left outer join
     tableC c
     on a.FK_tableC = c.pk_TableB
where PK_tableA = 100

此外,您需要在查询中使用正确的连接语法。而且,在 SELECT 子句中使用别名很好,但您也应该在 ON 和 WHERE 子句中使用它们。

【讨论】:

    【解决方案3】:

    尝试在表 B 和 C 上指定外连接 两个外连接.... 我认为它会起作用

    SELECT a.evi, a.time, a.date, 
           a.number, a.descr, a.x, 
           a.y, a.z,  a.FK_tableB, a.FK_tableC, 
           b.brand, b.type, 
           b.color, b.model, c.name, c.lastname, 
    FROM tableA a, 
         tableB b, 
         tableC c  
    WHERE PK_tableA = 100
    AND a.PK_tableB = b.FK_tableB(+)
    AND a.PK_tableB = c.FK_tableC(+)
    

    【讨论】:

    • 来自Oracle Documentation on Join Oracle 建议您使用FROM 子句OUTER JOIN 语法而不是Oracle 连接运算符。使用 Oracle 连接运算符 (+) 的外连接查询受以下规则和限制的约束,这些规则和限制不适用于 FROM 子句 OUTER JOIN 语法...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多