从2个表中生成2个select语句,然后将结果与第三个表连接起来

时间:2012-08-23 02:04:39

标签: sql sqlite

我有一个包含三个表的数据库:

表1

CREATE TABLE "A" ( "id" INTEGER PRIMARY KEY  NOT NULL 
                  ,"cat_id" INTEGER NOT NULL
                  ,"date" DATETIME NOT NULL
                  ,"amount" VARCHAR NOT NULL  DEFAULT (0.0)
                  ,"notes" VARCHAR)

表2:

CREATE TABLE "B" ( "id" INTEGER PRIMARY KEY  NOT NULL
                  ,"cat_id" INTEGER NOT NULL
                  ,"date" DATETIME NOT NULL
                  ,"amount" VARCHAR NOT NULL  DEFAULT (0.0)
                  ,"notes" VARCHAR)

表3:

CREATE TABLE "c" ( "id" INTEGER PRIMARY KEY  NOT NULL
                  ,"parent_id" INTEGER NOT NULL  DEFAULT (0)
                  ,"name" VARCHAR NOT NULL
                  ,"position" INTEGER NOT NULL
                  ,"importance" INTEGER NOT NULL  DEFAULT (0)
                  ,"transaction_type" VARCHAR NOT NULL  DEFAULT expenses
                  ,"icon" VARCHAR NOT NULL  DEFAULT default
                  ,"budget" INTEGER NOT NULL  DEFAULT 0
                  ,"status" INTEGER NOT NULL  DEFAULT 1)

我使用此语句从表AB中选择:

SELECT * FROM A
UNION ALL
SELECT * FROM B 
ORDER BY date 

我想将此select语句的结果与第三个表C一起加入:

RIGHT JOIN C on A.cat_id = C.id
RIGHT JOIN C on B.cat_id = C.id

我该怎么做?!

2 个答案:

答案 0 :(得分:3)

只需组合SQL语言的元素即可实现:

select ab.*, c.*
from ((SELECT *
       FROM A
      ) UNION ALL
      (SELECT *
       FROM B
      )
     ) ab right join
     C
     on ab.cat_id = c.id
ORDER BY date

这使得union成为子查询,然后从那里进行连接。

答案 1 :(得分:0)

你也可以加入联盟表)就像数学中的分配属性一样:

select *
from (
      (SELECT * FROM A right join C
        on ab.cat_id = c.id) 
      UNION ALL
      (SELECT * FROM B right join C
        on ab.cat_id = c.id)
     ) ab 
ORDER BY date

Hovewer,由于双重加入,这不是最佳方式。