简体   繁体   中英

How can I do this SQL Query?

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?

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.

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'
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'

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..

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