Assuming that company name and product name are primary keys at their relation, I don't understand how come that name of company can't be repeated in this query:
SELECT Company.name
FROM Company, Product
WHERE Company.name=Product.maker
AND Product.name IN
(SELECT Purchase.product
FROM Purchase
WHERE Purchase.buyer = ‘Joe Blow‘);
If S company made two products X,Y which Joe Blow bought them both, so at the beginning we would make a cartesian product for the condition "Company.name=Product.maker": SX, SY and for both, Product.name is in the set which compute, and therefor S should be output twice, no?
Without seeing your table structure or an error message, I can't really tell what's wrong. Your syntax appears to be correct.
However, your query could be improved by using better joins:
SELECT
c.name
FROM
Company c
INNER JOIN Product prod
ON c.name = prod.maker
INNER JOIN Purchase pch
ON prod.name = pch.product
WHERE
pch.buyer = 'Joe Blow'
I would recommend using explicit joins ( INNER JOIN
with an ON
join condition) instead of implicit joins (comma-separated tables and join conditions in the WHERE
clause) because it makes it clearer exactly how the tables are joined together.
I'd say, in majority of RDBMS your query will return two 'S'.
you can try it yourself here SQL FIDDLE
you can put distinct to have no duplicates
SELECT distinct Company.name
FROM Company, Product
WHERE Company.name=Product.maker
AND Product.name IN
(SELECT Purchase.product
FROM Purchase
WHERE Purchase.buyer = 'Joe Blow')
返回两个S是可以的,因为您从返回公司和产品的查询中预测公司名称,此查询的每一行都是唯一的,但是当您投影某些列时它们可能不是唯一的,或者可以使用DISTINCT
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.