2

我有一个父表 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 子句为真时,我如何返回数据。

4

3 回答 3

4

看来您想对查询执行“异或”(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进行尝试。

于 2012-07-16T14:19:16.710 回答
1

使用希望使用左外连接来保留表 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 子句中使用它们。

于 2012-07-16T14:17:58.150 回答
-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 a.PK_tableB = b.FK_tableB(+)
AND a.PK_tableB = c.FK_tableC(+)
于 2012-07-16T14:17:18.573 回答