SQL新手求助:关联Cars与Colors表查询车辆及对应颜色名称
Hey there! Since you're new to SQL, let's break this down step by step to get exactly the output you need.
Your goal is to list every car from the Cars table, along with its corresponding ColorName from the Colors table—even when a car doesn't have a ColorID (those should show NULL for ColorName).
The key here is using a LEFT JOIN (also called LEFT OUTER JOIN), which keeps all records from the left table (Cars) and matches them with records from the right table (Colors) where the join condition is met. If there's no match (like when ColorID is NULL in Cars), it still includes the car record and just puts NULL in the ColorName column.
Here's the SQL query you need:
SELECT c.CarID, c.Brand, cl.ColorName, c.Amount FROM Cars c LEFT JOIN Colors cl ON c.ColorID = cl.ColorID ORDER BY c.CarID;
Let's break down what this does:
FROM Cars c: We start with theCarstable, usingcas a shorthand alias to make the query cleaner and easier to read.LEFT JOIN Colors cl ON c.ColorID = cl.ColorID: This connects theColorstable (aliased ascl) toCarswhere theirColorIDvalues match. Since it's a LEFT JOIN, every row fromCarsis retained, even if there's no matchingColorIDinColors.- The
SELECTclause picks exactly the columns you specified in your expected output. ORDER BY c.CarID: Optional, but it ensures the results are ordered byCarIDjust like your desired output.
When you run this query, you'll get exactly the result you're looking for:
CarID | Brand | ColorName | Amount
1 | Ford | Blue | 23
2 | VW | Red | 15
3 | Opel | Red | 12
4 | Opel | NULL | 21
5 | Ford | NULL | 16
Just a quick note: If you used an INNER JOIN instead, the cars with NULL ColorID would be excluded from the results—so LEFT JOIN is definitely the right choice here when you need to keep all records from the first table.
内容的提问来源于stack exchange,提问作者Cooz

