我有三个表:产品, PC ,笔记本电脑,具有以下架构。
Product (maker, model, type)
PC (model, speed, ram, hd, price)
Laptop (model, speed, ram, hd, screen, price)
如何检索制造商A制作的所有产品的型号和价格?
我试过这个
SELECT *
FROM Product
WHERE maker = "A"
JOIN type.model,type.price;
和这个
SELECT *
FROM Product
JOIN Laptop ON Laptop.model;
......但没有运气。
编辑:如果我想让它更通用,我怎么能显示制造商A制造的任何产品的型号和价格,而不仅仅是笔记本电脑和PC?
答案 0 :(得分:3)
(SELECT product.maker, laptop.model, laptop.price
FROM Product
INNER JOIN laptop ON product.model = laptop.model
WHERE product.maker = "A" )
UNION
(SELECT product.maker, pc.model, pc.price
FROM Product
INNER JOIN pc ON product.model = pc.model
WHERE product.maker = "A" )
答案 1 :(得分:2)
SELECT model, price FROM Product INNER JOIN PC ON Product.model = PC.model WHERE maker = "A"
UNION
SELECT model, price FROM Product INNER JOIN Laptop ON Product.model = Laptop.model WHERE maker = "A"
答案 2 :(得分:2)
有些观点:
这是SQL:
SELECT PC.MODEL, PC.PRICE
FROM PC
JOIN PRODUCT ON PRODUCT.MODEL = PC.MODEL AND PRODUCT.MAKER = 'A'
UNION ALL
SELECT LAPTOP.MODEL, LAPTOP.PRICE
FROM LAPTOP
JOIN PRODUCT ON PRODUCT.MODEL = LAPTOP.MODEL AND PRODUCT.MAKER = 'A'
答案 3 :(得分:1)
看看一些mysql join tutorials,这样你就可以自己知道如何做了。
我认为product.model
同时引用pc.model
和laptop.model
。你可能想要使用mysql IF
:
SELECT IF(laptop.price IS NULL, pc.price, laptop.price) AS `price`, product.model
FROM product
LEFT JOIN pc ON (pc.model = product.model AND product.type = 'pc')
LEFT JOIN laptop ON (laptop.model = product.model AND product.type = 'laptop')
GROUP BY product.id
HAVING price IS NOT NULL