I got two mysql table like this
CREATE TABLE IF NOT EXISTS tbl1 (
`id` INTEGER(2) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT ,
`name` VARCHAR(20) NOT NULL
) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE IF NOT EXISTS tbl2 (
`tbl_id` INTEGER(2) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT ,
`id2` INTEGER(2) UNSIGNED NOT NULL ,
`email` VARCHAR(20) NOT NULL ,
FOREIGN KEY (`id2`) REFERENCES tbl1(`id`)
) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
Here is example data in tbl1
1 hello
2 world
3 happy
4 end
and example data in tbl2
2 1 me@mail
3 2 my@mail
4 4 you@mail
now I want to select name and email joining two table. Here is the sql
select name,email from tbl1 t1,tbl2 t2 where t2.id2 = t1.id;
with it i’m getting
hello me@mail
world my@mail
end you@mail
but I want all row from tbl1
hello me@mail
world my@mail
happy null or nothing or 0
end you@mail
here i am stuck. any help will be appreciated.
thanks in advance.
You should use a
LEFT JOIN:See SQL Fiddle with Demo.
Your current query is using an
INNER JOINwhich will only return the rows that are matching in both tables. TheLEFT JOINwill return all records intbl1even if there is no matching row intbl2.If you need help learning join syntax here is a visual explanation of joins