Sql查询获取所有帐户表记录及其子记录

时间:2012-02-17 10:22:55

标签: sql oracle

我有两个表与1:M的关系:帐户(父)和'付款'(孩子)。 “付款”表格中有一个“类型”列,其值可以是“付费”,“付费”或“未付款”。

现在我需要编写一个查询,它可以获取所有帐户表记录及其子记录。但是在子表中,它应该首先检查是否存在父帐户表的任何“付费”类型记录。如果是,那么它将只选择(不是其他类型)。如果子表中不存在“付费”类型记录,则它将检查“将付费”类型的子记录并仅获取它们。

2 个答案:

答案 0 :(得分:1)

假设你至少有:

CREATE TABLE account (
    id INTEGER NOT NULL PRIMARY KEY
);

CREATE TABLE payment (
    account_id INTEGER NOT NULL REFERENCES account(id),
    type ENUM ('Paid', 'will-Pay', 'Not-paid')
);

'支付'记录和'将支付'记录在同一答案中:

SELECT
    account.*, payment.*
FROM
    account
    INNER JOIN payment
        ON (payment.account_id = account.id)
WHERE payment.type IN ('Paid', 'will-Pay');

'付费'记录和'将支付'记录在单独的答案中:

-- Fetch 'Paid' records
SELECT
    account.*, payment.*
FROM
    account
    INNER JOIN payment
        ON (payment.account_id = account.id)
WHERE payment.type = 'Paid';

-- Fetch 'will-Pay' records
SELECT
    account.*, payment.*
FROM
    account
    INNER JOIN payment
        ON (payment.account_id = account.id)
WHERE payment.type = 'will-Pay';

答案 1 :(得分:0)

尝试:

SELECT p.*
FROM account a
INNER JOIN payment p ON p.account_id = a.id
WHERE p.type = 'Paid' or 
      (p.type = 'will-Pay' and not exists
       (select null from payment p1 where p1.account_id = a.id and p1.type = 'Paid')
      )