如果子查询没有值sql,则重新生成null

时间:2017-11-13 12:57:42

标签: sql oracle subquery

如果此查询没有B值,但是有A值,那么在没有值的情况下我可以为空吗?

SELECT A, B
FROM 
(SELECT title as A
 FROM TABLE1 
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'),

(SELECT title as B
 FROM TABLE1 
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')

例如,此表必须显示

  A        B
---------------
Computer  null

但现在只有当Id具有A类和B类

时才会显示这些值

3 个答案:

答案 0 :(得分:1)

没有LEFT CROSS JOIN这样的东西,但您可以使用LEFT JOIN实现它:

SELECT a.A, b.B
FROM (SELECT title as A
      FROM TABLE JOIN
           TABLE2
           ON TABLE_TABLE2_ID = TABLE2_ID JOIN
           TABLE3
           ON TABLE_TABLE3_ID = TABLE3_ID
      WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'
     ) a, LEFT JOIN
     (SELECT title as B
      FROM TABLE JOIN
           TABLE2
           ON TABLE_TABLE2_ID = TABLE2_ID JOIN
           TABLE3
           ON TABLE_TABLE3_ID = TABLE3_ID
      WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B'
     ) b
     ON 1 = 1;

答案 1 :(得分:1)

目前还不清楚您有哪些数据,但是当您期望每<build> <resources> <resource> <directory>src/main/webapp</directory> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> ... 行为零或一行时,您可以使用PIVOT并避免自我加入:

SQL Fiddle

Oracle 11g R2架构设置

TABLE_TYP

查询1

CREATE TABLE TABLE1 ( table1_table2_id, table1_table3_ID ) AS
SELECT 1, 2008 FROM DUAL;

CREATE TABLE TABLE2 ( table2_ID, table_typ ) AS
SELECT 1, 'A' FROM DUAL;

CREATE TABLE TABLE3 ( table3_ID, title ) AS
SELECT 2008, 'Computer' FROM DUAL;

<强> Results

SELECT *
FROM   (
  SELECT title,
         table_typ
  FROM   TABLE1 
         INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
         INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
  WHERE  TABLE1_TABLE3_ID = 2008
  AND    TABLE_TYP IN ( 'A', 'B' )
)
PIVOT ( MAX( title ) FOR Table_Typ IN ( 'A' AS A, 'B' AS B ) )

如果您的子查询期望返回多行,那么您将无法使用此精确方法(但仍然may be able to use PIVOT,并且根据您的要求避免自联接。)

答案 2 :(得分:0)

SELECT A, B
FROM 
(SELECT title as A
FROM TABLE 
INNER JOIN TABLE2 ON TABLE_TABLE2_ID = TABLE2_ID
INNER JOIN TABLE3 ON TABLE_TABLE3_ID = TABLE3_ID
WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A')AA
left join
(SELECT title as B
FROM TABLE 
INNER JOIN TABLE2 ON TABLE_TABLE2_ID = TABLE2_ID
INNER JOIN TABLE3 ON TABLE_TABLE3_ID = TABLE3_ID
WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')BB
on AA.A=BB.B

Hope this will solve your problem...