我在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