我在MySQL(5.1)中有3個表: account,bank_account_data和investment_account_data。MySQL左連接問題
表是定義如下: (注:這是一個簡化版本的實際表具有更多的列,銀行和投資數據有不是需要這種特殊情況下,但在其他地方需要不同的信息)
CREATE TABLE account
(
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
type ENUM ('INVESTMENT', 'BANK') NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
CREATE TABLE investment_account_data
(
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
account_id BIGINT UNSIGNED NOT NULL,
as_of_date TIMESTAMP NULL DEFAULT NULL,
total_balance NUMERIC(12, 4) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (account_id) REFERENCES account (id),
CONSTRAINT unique_per_account_and_date UNIQUE (account_id, as_of_date)
) ENGINE=InnoDB;
CREATE TABLE bank_account_data
(
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
account_id BIGINT UNSIGNED NOT NULL,
as_of_date TIMESTAMP NULL DEFAULT NULL,
current_balance NUMERIC(12, 4) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (account_id) REFERENCES account (id),
CONSTRAINT unique_per_account_and_date UNIQUE (account_id, as_of_date)
) ENGINE=InnoDB;
目前我在帳戶表中只有一個帳戶,id = 1,type ='INVESTMENT' ,我在investment_account_data表中有一條記錄(id = 1,account_id = 1,total_balace = 15000,as_of_data ='2011 -03-02 00:00:00')
the bank_account_data沒有行。
運行下面的查詢(奇怪)不返回行:
SELECT A.id as account_id,
COALESCE(BD.as_of_date, ID.as_of_date) as as_of_date,
COALESCE(BD.current_balance, ID.total_balance) as balance
FROM account A
LEFT JOIN bank_account_data BD ON (BD.account_id = A.id and A.type='BANK')
LEFT JOIN investment_account_data ID ON (ID.account_id = A.id and A.type='INVESTMENT')
WHERE A.id=1
但是這一次返回一行(預期):
SELECT A.id as account_id,
COALESCE(BD.as_of_date, ID.as_of_date) as as_of_date,
COALESCE(BD.current_balance, ID.total_balance) as balance
FROM account A
LEFT JOIN investment_account_data ID ON (ID.account_id = A.id and A.type='INVESTMENT')
LEFT JOIN bank_account_data BD ON (BD.account_id = A.id and A.type='BANK')
WHERE A.id=1
任何想法,爲什麼我看到這些結果?
此外,如果我從連接中刪除A.type條件它也將返回一行。
我會通過將測試行的類型字段更改爲BANK來測試這些查詢。假定第一個查詢會返回一行,第二個查詢將不返回任何行。 – 2011-03-04 01:36:40
更改爲鍵入'BANK'確實會在第一個查詢中返回一行,而在第二個查詢中不會返回任何行。 – talg 2011-03-04 01:39:58