Reputation: 67960
I'm learning SQL and I'm having trouble with a query.
I have the following tables:
[ laptop ]
price
model[ pc ]
price
model
speed[ printer ]
price
model
color[ product ]
model
maker
How can I write a query that will return the model and price of any product which is made by maker "A"?
I'm having issues because Laptop, PC, and Printer all have a "model" and "price", so how do I select them based on the condition of their maker in the "Product" table?
Upvotes: 0
Views: 139
Reputation: 1585
I think your table structure need to rebuild and normalization ... with right structure you can fetch result correctly and efficiency. i think the proper structure for your table is:
table: Product
id
name
.
.
price
table: ProductFeature
attribute
value
product_id
in first table store all yours product with common attribute, and in second table you could store the other feature like color, speed, .... etc , using forign key..
Upvotes: 0
Reputation: 47968
SELECT T.model, T.price
FROM (SELECT model, price FROM laptop
UNION ALL
SELECT model, price FROM pc
UNION ALL
SELECT model, price FROM printer) T
JOIN product p ON p.model = T.model
WHERE p.maker = 'A'
Upvotes: 1
Reputation: 10610
SELECT * FROM
(
SELECT model,price FROM laptop
UNION ALL
SELECT model,price FROM pc
UNION ALL
SELECT model,price FROM printer
) all_items
INNER JOIN product p ON all_items.model = p.model
WHERE p.maker = 'A'
You don't have to put conditions in three places. Only at the end.
Upvotes: 3
Reputation: 125488
You could UNION
the results together
SELECT
l.model,
l.price
FROM
laptop l
INNER JOIN
product p
ON
l.model = p.model
WHERE
p.maker = 'A'
UNION ALL
SELECT
pc.model,
pc.price
FROM
pc pc
INNER JOIN
product p
ON
l.model = p.model
WHERE
p.maker = 'A'
UNION ALL
SELECT
pr.model,
pr.price
FROM
printer pr
INNER JOIN
product p
ON
l.model = p.model
WHERE
p.maker = 'A'
Upvotes: 1