简体   繁体   中英

SQL - How can you use WHERE instead of LEFT/RIGHT JOIN?

since I am a bit rusty, I was practicing SQL on this link and was trying to replace the LEFT JOIN completly with WHERE. How can i do this so it does the same thing as the premade function in the website?

What I tried so far is:

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID OR Customers.CustomerID != Orders.CustomerID
Order by Customers.CustomerName; 

Thanks in advance for your help.

You are trying to replace

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID

with

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers, Orders
WHERE ???

this is doomed to failure. Consider Customers has two rows and Orders has zero. The outer join will return two rows.

The cross join ( FROM Customers, Orders ) will return zero rows.

In standard SQL a WHERE clause can only reduce the rows from that - not increase them so there is nothing you can put for ??? that will give your desired results.

Before ANSI-92 joins were introduced some systems used to have proprietary operators for this, such as *= in SQL Server but this was removed from the product .

This may work for you.

SELECT 
   c.CustomerName, 
   o.OrderID
FROM Customers c
LEFT JOIN Orders o 
on c.CustomerID = o.CustomerID 
Order by c.CustomerName; 

If you are trying to replace this:

SELECT c.CustomerName, o.OrderID
FROM Customers c LEFT JOIN
     Orders o
     ON c.CustomerID = o.CustomerID
ORDER BY c.CustomerName; 

Then you can use UNION ALL :

SELECT c.CustomerName, o.OrderID
FROM Customers c JOIN
     Orders o
     ON c.CustomerID = o.CustomerID
UNION ALL
SELECT c.CustomerName, o.OrderID
FROM Customers c 
WHERE NOT EXIST (SELECT 1 FROM Orders o WHERE c.CustomerID = o.CustomerID)
ORDER BY CustomerName

However, the LEFT JOIN is really a much better way to go.

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