且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server:具有WHERE子句的多个表联接

更新时间:2023-01-28 17:34:02

在使用LEFT JOINRIGHT JOIN时,将过滤器放在WHERE还是JOIN中都会有所不同.>

请看我前段时间写的一个类似问题的答案:
由于获得两个不同的结果集,这两个查询有何区别?

简而言之:

  • 如果将其放入WHERE子句中(就像您所做的那样,与该计算机无关的结果将被完全过滤掉
  • 如果将其放入JOIN中,则与该计算机不相关的结果将显示在查询结果中,仅具有NULL
    ->这就是你想要的

I'm using SQL Server and I'm having a difficult time trying to get the results from a SELECT query that I want. I've tried joining in different orders and using subqueries but nothing quite works the way I want. Take this contrived example of software applications, with different version levels, that might be installed on peoples computers.

I need to perform a JOIN with a WHERE, but for some reason I can't get the results I want.

Maybe I'm looking at my data wrong, I'm not quite sure why I can't get this to work.

Application table

ID  Name
1   Word
2   Excel
3   Powerpoint

Software Table (contains version information for different applications)

ID  ApplicationID   Version
1   1             2003
2   1             2007
3   2             2003
4   2             2007
5   3             2003
6   3             2007

Software_Computer junction table

ID  SoftwareID  ComputerID
1   1           1
2   4           1
3   2           2
4   5           2

Computer table

ID  ComputerName
1   Name1
2   Name2

I want a query that I could run where I select a specific computer to display what software version and application is has, but I also want it to display what application it does not have(the version would be a NULL since it doesn't have that software on it)

SELECT Computer.ComputerName, Application.Name, Software.Version
FROM Computer
JOIN Software_Computer
    ON Computer.ID = Software_Computer.ComputerID
JOIN Software
    ON Software_Computer.SoftwareID = Software.ID
RIGHT JOIN Application
    ON Application.ID = Software.ApplicationID
WHERE Computer.ID = 1 

I want the following result set

ComputerName   Name          Version
Name1          Word          2003
Name1          Excel         2007
Name1          Powerpoint    NULL

But I just get

Results
ComputerName   Name          Version
Name1          Word           2003
Name1          Excel          2007

I thought the RIGHT JOIN would include all the results in the application table, even if they aren't associated with the computer. What am I missing/doing wrong?

When using LEFT JOIN or RIGHT JOIN, it makes a difference whether you put the filter in the WHERE or into the JOIN.

See this answer to a similar question I wrote some time ago:
What is the difference in these two queries as getting two different result set?

In short:

  • if you put it into the WHERE clause (like you did, the results that aren't associated with that computer are completely filtered out
  • if you put it into the JOIN instead, the results that aren't associated with that computer appear in the query result, only with NULL values
    --> this is what you want