也许我错过了一些愚蠢的东西,但是......
我有三个 m-to-m 关系表:
CREATE TABLE tbl_users (
usr_id INT NOT NULL AUTO_INCREMENT ,
usr_name VARCHAR( 64 ) NOT NULL DEFAULT '' ,
usr_surname VARCHAR( 64 ) NOT NULL DEFAULT '' ,
usr_pwd VARCHAR( 64 ) NOT NULL ,
usr_level INT( 1 ) NOT NULL DEFAULT 0,
PRIMARY KEY ( usr_id )
) ENGINE = InnoDB;
CREATE TABLE tbl_houses (
house_id INT NOT NULL AUTO_INCREMENT ,
city VARCHAR( 100 ) DEFAULT '' ,
address VARCHAR( 100 ) DEFAULT '' ,
PRIMARY KEY ( house_id )
) ENGINE = InnoDB;
CREATE TABLE tbl_users_houses (
user_id INT NOT NULL ,
house_id INT NOT NULL ,
INDEX user_key (user_id),
FOREIGN KEY (user_id) REFERENCES tbl_users(usr_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
INDEX house_key (house_id) ,
FOREIGN KEY (house_id) REFERENCES tbl_houses(house_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE = InnoDB;
在链接表中,我有两条记录:
user_id house_id
1 1
1 2
现在,尝试选择所有房屋:
select * from tbl_houses AS H
left join tbl_users_houses AS UH on H.house_id = UH.house_id
where UH.user_id = 2;
为什么我没有数据而不是所有房屋?