You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the Cars table, using c as a shorthand alias to make the query cleaner and easier to read.
  • LEFT JOIN Colors cl ON c.ColorID = cl.ColorID: This connects the Colors table (aliased as cl) to Cars where their ColorID values match. Since it's a LEFT JOIN, every row from Cars is retained, even if there's no matching ColorID in Colors.
  • The SELECT clause picks exactly the columns you specified in your expected output.
  • ORDER BY c.CarID: Optional, but it ensures the results are ordered by CarID just 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:15:16