内连接

时间:2015-08-14 22:15:27

标签: mysql sql

关于MySQL的表格

表供应商

---------------------------------------------------
SupplierID |    SupplierName |  ContactName Address
---------------------------------------------------

表产品

-----------------------------------------------
ProductID | ProductName |SupplierID Unit| Price
-----------------------------------------------

查询

SELECT Suppliers.SupplierName
       , ProductName
       , Price
FROM Products 
INNER JOIN (SELECT SupplierID
                   , MAX(Price) AS maxPrice
            FROM Products
            GROUP BY SupplierID) as gp ON Products.Price = gp.maxPrice
INNER JOIN Suppliers ON Suppliers.SupplierID = Products.SupplierID;

我想要做的是获取产品的名称,供应商的名称及其各自的价格,基于每个供应商最昂贵产品的价格(即子查询提取的内容),但其余的查询不起作用,不知道为什么

SQL错误

Syntax error (missing operator) in query expression 'Products.Price =
gp.maxPrice INNER JOIN Suppliers ON Suppliers.SupplierID =
Products.SupplierID'.

2 个答案:

答案 0 :(得分:1)

SELECT Suppliers.SupplierName,ProductName,Price 
FROM Products 
INNER JOIN (SELECT SupplierID,  MAX(Price) maxPrice 
            FROM Products GROUP BY SupplierID) gp 
ON Products.Price = gp.maxPrice and products.supplierid = gp.supplierid
INNER JOIN Suppliers ON Suppliers.SupplierID = Products.SupplierID;

你可以试试这个。 join也已在子查询的supplierid上完成。另外,请确保在select子句中的列名前包含表名,以避免歧义。

答案 1 :(得分:1)

SELECT Suppliers.SupplierName,ProductName,Price FROM (Products 
INNER JOIN (SELECT SupplierID,  MAX(Price) AS maxPrice FROM Products GROUP BY SupplierID) as gp ON Products.Price = gp.maxPrice)
INNER JOIN Suppliers ON Suppliers.SupplierID = Products.SupplierID;

有效吗?