SQL新手求助:查询与客户Bob同区域餐厅售卖的独特披萨
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: TheDISTINCTkeyword 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, usingcas 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

