简体   繁体   English

如何在两个以上的表上执行Sql Join查询?

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

I have a table named "tbl_category" which contains the following fields: 我有一个名为“ tbl_category”的表,其中包含以下字段:

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: 另一个表是“ tbl_sub_category”,它具有以下字段:

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. 现在,我想显示sub_category及其相应的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 从tbl_category中选择c.category_title,s.sub_category c左外部联接tbl_sub_category s ON c.category_id = s.category_id

CategoryID in subcategory table cannot be auto-increment. 子类别表中的类别ID不能自动递增。

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. 上面的示例将仅显示tbl_sub_category中具有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. INNER JOIN声明仅返回具有外键关系的行,而FROM则以tbl_sub_category开头,以确保我们仅查看子类别。 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. 您可以轻松地颠倒这两个,以便将FROM放在tbl_category上,将INNER JOIN放在tbl_sub_category上,这将产生相同的结果,但是在此示例中,您更加清楚地表明您对子类别感兴趣,而对类别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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