简体   繁体   English

用Where子句加入两个表

[英]Joining Two Tables with Where Clause

I have two tables. 我有两张桌子。 Cat and Data. 猫和数据。

Cat
  Cat_Serno
  Cat_Name 

 Data
  Data_Serno
  Data_Name
  Data_Cat_ID
  Data_Project_ID

When i Am doing a regular join I am getting 当我正在进行定期加入时,我正在接受

 SELECT t1.*,t2.* 
 FROM Cat t1 
      LEFT JOIN Data t2 ON t1.Cat_Serno = t2.Data_Cat_Id

在此输入图像描述

but when I apply a where condition on Project_Id it gives me only one column. 但是当我在Project_Id上应用where条件时,它只给我一列。 I want to Display all the category and Null if there is no related data in the Data table along with the where clause on the Project_Id. 如果Data表中没有相关数据以及Project_Id上的where子句,我想显示所有类别和Null。 It should also contain Null if I am using a where clause with a project_id without any value in the Data table (eg: where Project_Id=2) even if 2 is not present in the Data Table. 如果我使用带有project_id的where子句而不包含Data表中的任何值(例如:其中Project_Id = 2),它也应该包含Null,即使数据表中不存在2。

When I do it with Project_Id=2 which is not existing in Data Table I only get one Record with Null Values. 当我使用Project_Id = 2(数据表中不存在)时,我只获得一个具有空值的记录。 在此输入图像描述

If you include column of table Data in where clause, your join will almost act as inner join , so if you want all records of Cat table , you should not include any column of Data table in where clause, still if you want to apply condition you can include it in " on " in join Try this, 如果在where子句中包含table Data column ,则您的join几乎将充当inner join ,因此如果您想要Cat table所有记录,则不应在where子句中包含任何Data表column ,如果您想要应用条件你可以把它包含在join中的“ on ”试试这个,

SELECT t1.*,t2.* 
 FROM Cat t1 
      LEFT JOIN Data t2 ON t1.Cat_Serno = t2.Data_Cat_Id
          and Project_Id=2

You have to add the where condition with the required values and add an OR condition with IS NULL 您必须使用所需的值添加where条件,并使用IS NULL添加OR条件

Example: 例:

WHERE (DataName = 'Data_One' OR DataName IS NULL)

Please note, that NULL is not equals to any values (including NULL), so you have to handle it. 请注意,NULL不等于任何值(包括NULL),因此您必须处理它。

Another way: 其他方式:

WHERE COALESCE(DataName, 'n/a') IN ('Data_One', 'n/a')

If you want to return records from both Data and Cat, when there is no matching records in the opposite table, do a FULL OUTER JOIN, instead of a LEFT/RIGHT join. 如果要从Data和Cat返回记录,当相对表中没有匹配的记录时,请执行FULL OUTER JOIN,而不是LEFT / RIGHT join。

Furthermore, to filter records from either table without filtering the entire result set, apply your conditions in the ON part of the statement, rather than the WHERE part of the statement. 此外,要从任一表中过滤记录而不过滤整个结果集,请在语句的ON部分应用条件,而不是语句的WHERE部分。 For example: 例如:

SELECT t1.*, t2.* FROM Cat t1 FULL OUTER JOIN Data t2 
     ON t1.Cat_Serno = t2.Data_Cat_Id 
    AND t2.Data_Project_Id = 2

Try: 尝试:

WHERE t2.project_id = ...
OR t2.project_id IS NULL;

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

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