简体   繁体   中英

SQL Query help - Joins

I have a couple of SQL tables which are:

customer(Id, Name, Address, PhoneNumber);
station (Id, City, Country, Location);
car(Id, Reg, Type, Milage);
contract(CustId, StationId, CarId);

I need to use these tables to find all customers who have rented a BMW. I have written out my query as:

SELECT *
FROM CUSTOMER, CAR, CONTRACT
WHERE CUSTOMER.ID = CONTRACT.CUSTID
AND CAR.TYPE = "BMW";

Would that be correct? My thinking was I need to join the tables as there is no way of knowing what customer has rented which car, but I feel like I might be doing something wrong? Any help would be appreciated.

No, your query is not correct -- it is incorrect logically and it is written poorly.

The better way to write the query is to use proper, explicit, standard JOIN syntax:

SELECT *
FROM CONTRACT co JOIN
     CUSTOMER cu
     ON co.CUSTID = cu.ID JOIN
     CAR ca
     ON co.CARID = ca.ID  -- this is a guess
WHERE ca.TYPE = 'BMW';

Notes:

  • You are missing the JOIN condition between CONTRACT and CAR (presumably). With explicit JOIN syntax, this is pretty obvious.
  • I am guessing at the right JOIN condition for CAR .
  • Use single quotes for string constants. That is the SQL standard, although some databases do allow double quotes as well.
  • SELECT * is usually to be discouraged. It is generally better practice to list the columns, especially in this case when the same column name might appear in different tables.
SELECT co.Id as ContractId , Name, Address, PhoneNumber,
cu.Id as CustId , City, Country, Location,
ca.Id as CarId, Reg, Type, Milage,
FROM CONTRACT co JOIN
CUSTOMER cu
ON co.CUSTID = cu.ID JOIN
CAR ca
ON co.CARID = ca.ID
STATION st
ON co.StationId = st.ID 
WHERE ca.TYPE = 'BMW';

You need to mention Column names explicitly because there will be name conflict for field Id which is common across many tables

PS: Just modifying query from Gordon Linoff answer on the same question

This should help: (You do not need to worry about Station as per your requirement)

SELECT distinct cus.*
FROM CONTRACT con 
JOIN CUSTOMER cus ON con.CUSTID = cus.ID 
JOIN CAR car ON co.CARID = car.ID 
WHERE car.TYPE = 'BMW';

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