0

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

表格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)

我使用此语句从表中进行选择,A并且B

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

我怎样才能做到这一点?!

4

2 回答 2

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

这使得联合全部成为子查询,然后从那里进行连接。

于 2012-08-23T02:19:13.087 回答
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

但是,由于双重连接,这不是最好的方法。

于 2012-08-23T02:34:03.480 回答