简体   繁体   中英

How to perform Sql Join Query on more than two tables?

I have a table named "tbl_category" which contains the following fields:

category_id int auto_increment primary key,
category_title varchar(max),
category_description varchar(max) //is the foreign key in "tbl_sub_category"

And another table is "tbl_sub_category" which have the following fields:

sub_category_id int auto_increment primary key,
sub_cateogry varchar(max),
cateogry_id int auto_increment

Now, I want to display sub_category with its corresponding category_title. Can any help me out?

Use this query

SELECT c.category_title, s.sub_category
FROM tbl_category c
INNER JOIN tbl_sub_category s ON c.category_id = s.category_id
SELECT sub_category,category_title FROM tbl_category,tbl_sub_category 
 WHERE tbl_category.category_id=tbl_sub_category.category_id;

This is with a minor modification on the previous query, The previous queries would work fine if corresponding to each category an entry is available in subcategory table. If it is not the case, use outer join.

SELECT c.category_title, s.sub_category FROM tbl_category c LEFT OUTER JOIN tbl_sub_category s ON c.category_id = s.category_id

CategoryID in subcategory table cannot be auto-increment.

SELECT
    s.sub_category_id,
    s.sub_cateogry,
    c.category_title
FROM
    tbl_sub_category s
INNER JOIN
    tbl_category c
    ON s.cateogry_id = c.category_id

The above example will only ever display items that are in the tbl_sub_category that have a corresponding foreign key in tbl_category. The INNER JOIN is stating to only return rows that have the foreign key relationship, while the FROM starts with tbl_sub_category which ensures we're only looking at sub categories. You can easily reverse these two so that the FROM is on the tbl_category and the INNER JOIN is on the tbl_sub_category which would produce the same results, but in this example you're being more explicit that you're interested in the sub categories and not the categories.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM