如何正确处理sqlite表自引用?

时间:2015-10-11 02:31:13

标签: sqlite

我为一个小牛群创建了一个sqlite数据库。

CREATE TABLE Animals
(
animal_id PRIMARY KEY,
animal_name CHAR(15) NULL,
date_born DATE NULL,
f_parent REFERENCES Animals (animal_id) NULL,
m_parent REFERENCES Animals (animal_id) NULL,
date_purchased DATE NULL,
registered BIT NOT NULL,
gender CHAR(1) NOT NULL CHECK(gender IN ("M","F")),
breed INTEGER NOT NULL REFERENCES breed (breed_id)
);


CREATE TABLE termination (term_key INTEGER PRIMARY KEY, animal_id   INTEGER, term_date DATE, sold BIT, price SMALLMONEY, comp_market_price SMALLMONEY, comp_market_tier TEXT);

我有这样的声明:

SELECT a1.animal_id, a1.animal_name, a1.f_parent, t1.term_date,   t1.price, t1.comp_market_price, t1.comp_market_tier
FROM Animals AS a1, termination AS t1
WHERE a1.animal_id = t1.animal_id
AND a1.f_parent NOT NULL;

结果是:

id#|'animal name'|'parent id#'|已售出日期......

15 | some name | 4 | 2014-05-26 ...

...

这是正确的和我想要的,除了代替'父ID#'我想要父母的名字。父ID#是与后代在同一个表中的一个键(正如你从我上面的create语句中看到的那样),但我无法弄清楚如何处理这个自引用。我知道这个问题很常见,我尝试过查看表,多个连接等等都无济于事。请显示我如何打印相同结果的代码段,显示父母姓名代替父ID#/密钥号。

非常感谢你!

1 个答案:

答案 0 :(得分:1)

这样的事可能吗?

select a.animal_id, a.animal_name,
       (select animal_name
          from animals
          where a.f_parent = animal_id) as parent,
       t.term_date, t.price, t.comp_market_price, t.comp_market_tier
  from animals as a, termination as t using(animal_id)
  where a.f_parent not null;

还是这个? (更好的执行计划)

select a.animal_id as id, a.animal_name as name,f.animal_name as mother,
       t.term_date, t.price, t.comp_market_price, t.comp_market_tier
  from animals as a, termination as t using(animal_id),
       animals f
  where a.f_parent = f.animal_id
    and a.f_parent is not null;