I want a query from my 3 table, but i dont know which JOIN should I use. I want to display all of table2’s item_id and item_name, also show stat and shipped from table3 even if its NULL. Also, user_id from table1.
Table1
CREATE TABLE table1(
id NOT NULL AUTO_INCREMENT,
user_name varchar(255),
);
Table 2
CREATE TABLE table2(
id NOT NULL AUTO_INCREMENT,
item_name varchar(255),
);
Table 3
CREATE TABLE table3 (
id int NOT NULL AUTO_INCREMENT,
user_id int NOT NULL,
item_id int NOT NULL,
stat tinyint NOT NULL,
shipped tinyint NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES table1(id),
FOREIGN KEY (item_id) REFERENCES table2(id)
);
I tired LEFT INNER JOIN, but I only got table3.
Thank you!
4
Answers
You can start from
table2
since this is the mandatory one andLEFT JOIN
with the other two tablesAs you want all entries from tabl2 you should start there and add the other tables using
left outer join
or shortleft join
The below query starts at
table2
as you need to show all items even if their status is null. Assuming that the relationship betweentable2
andtable3
is a 1-1 then the below query will show you 1 line per item.You can use a LEFT JOIN to achieve this. The LEFT JOIN will ensure that all records from table2 are included in the result, even if there are no matching records in table3