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

SQL新手求助:查询与客户Bob同区域餐厅售卖的独特披萨

Query for Unique Pizzas Sold in Bob's Area Restaurants

Hey there! Since you're new to SQL, let's walk through how to get the unique pizzas sold by restaurants in Bob's neighborhood—no jargon overload, just clear steps. 😊

First, we need to pin down Bob's area using the Customers table. Then, we'll connect that area to the Restaurants table to find all spots in the same location. Finally, we'll link those restaurants to the Sells table to grab every pizza they offer, making sure we only get each pizza once.

The SQL Query (Using Joins)

This is a clean, readable approach for beginners, as it shows how tables connect directly:

SELECT DISTINCT s.pizza
FROM Customers c
JOIN Restaurants r ON c.area = r.area
JOIN Sells s ON r.rname = s.rname
WHERE c.cname = 'Bob';

Let's break down each part:

  • SELECT DISTINCT s.pizza: The DISTINCT keyword ensures we don't get duplicate pizza names (even if multiple restaurants sell the same pizza, or one restaurant lists it multiple times).
  • FROM Customers c: We start with the Customers table, using c as a shorthand alias to keep the code tidy.
  • JOIN Restaurants r ON c.area = r.area: This links Bob's record to all restaurants in his area—only restaurants matching Bob's neighborhood stay in the result.
  • JOIN Sells s ON r.rname = s.rname: Now we connect those local restaurants to the pizzas they actually sell.
  • WHERE c.cname = 'Bob': This filters our chain to only start with Bob's customer data, so we're only looking at his area.

Alternative Query (Using Subqueries)

If you prefer a "step-by-step" nested approach, this version might feel more intuitive:

SELECT DISTINCT pizza
FROM Sells
WHERE rname IN (
    -- Get all restaurants in Bob's area
    SELECT rname
    FROM Restaurants
    WHERE area = (
        -- First, find Bob's area
        SELECT area
        FROM Customers
        WHERE cname = 'Bob'
    )
);

This works by first grabbing Bob's area in the innermost subquery, then finding all restaurants in that area, then pulling all pizzas sold by those restaurants. Same end result—just a different way to structure the logic.

Either query will get you exactly what you need! If any part feels confusing, just ask and we can unpack it further.

内容的提问来源于stack exchange,提问作者user144794

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:30:46