Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL LEFT JOIN returns empty resultset

Tags:

sql

mysql

maybe I miss something stupid but...
I have three tables in m-to-m relation:

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;

Into the link table I have two records:

user_id  house_id
  1         1
  1         2

Now, trying to select all houses with:

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;

Why I get no data instead of all houses?

like image 358
Barzo Avatar asked Jan 25 '26 01:01

Barzo


1 Answers

Because of this line:

where UH.user_id = 2;

This is only true if UH.user_id is non-null, so it effectively excludes any case where you have a house without a matching row in UH, which is the point of using a LEFT JOIN.

If you want all houses, and UH data where there is a match, use this:

select * from tbl_houses AS H 
  left join tbl_users_houses AS UH on H.house_id = UH.house_id and UH.user_id = 2;
like image 68
Bill Karwin Avatar answered Jan 27 '26 15:01

Bill Karwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!