2017-04-25 129 views
0

我想执行这个查询:SQL INNER JOIN实体

-- The most expensive item sold ever 
SELECT 
    c.itemID, c.itemName 
FROM 
    item AS c 
JOIN 
    (SELECT 
     b.itemID as 'itemid', MAX(b.item_initialPrice) AS 'MaxPrice' 
    FROM 
     buyeritem AS a 
    INNER JOIN 
     item AS b ON a.item_ID = b.itemID) AS d ON c.itemID = d.itemid 
GROUP BY 
    c.itemID, c.itemName; 

item表看起来像这样:

create table item 
(
    itemID int IDENTITY(1000, 1) NOT NULL, 
    itemName varchar(15) NOT NULL, 
    Item_desc varchar(255), 
    Item_initialPrice MONEY, 
    ItemQty int, 
    ownerID int NOT NULL, 
    condition varchar(20) NOT NULL, 

    PRIMARY KEY (itemID), 

    FOREIGN KEY (ownerID) REFERENCES seller (sellerID) 
); 

的问题是,列item.itemID无效在选择列表中,因为它是不包含在聚合函数或GROUP BY子句中。我试图在末尾添加一个group by子句

group by c.itemID, c.itemName 

但是我仍然得到同样的错误?我真的不知道问题来自哪里。

我也有这个疑问

-- The most active seller(the one who has offered the most number of items) 
SELECT 
    a.ownerID, b.sellerName 
FROM 
    item AS a 
INNER JOIN 
    seller AS b ON a.ownerID = b.sellerID 
GROUP BY 
    a.ownerID, b.sellerName 
ORDER BY 
    COUNT(a.itemID) DESC; 

我想补充itemQtyitemownerIDsellerName上述以来,这将是实现这一最好的方法是什么?

+0

获得第一个直接查询数据库中的工作,然后担心JDBC代码。 –

回答

0

只是编写不同组而不是Group By作为Group By不能在集合函数中使用,例如sum,max等select语句中缺少的查询语句。例如,我写了第二个查询语句

SELECT distinct c.itemID, c.itemName 
FROM item AS c 
JOIN (
SELECT b.itemID as itemid, MAX(b.item_initialPrice) AS MaxPrice FROM buyeritem AS a 
INNER JOIN item AS b ON a.item_ID = b.itemID 
GROUP BY b.itemID) as d 
ON c.itemID = d.itemid ; 

对于第二个查询

Select a.* from 
(
SELECT a.ownerID, b.sellerName, count(distinct a.ITEM_ID) as item_qty 
FROM item AS a 
INNER JOIN seller AS b ON a.ownerID = b.sellerID 
GROUP BY a.ownerID,b.sellerName 
) a 
order by item_qty DESC 
+0

@ a_horse_with_no_name感谢您指出了这一点。修复。现在它应该可以在大多数DBMS –

+0

tnx中获得反馈,我之前也检查过不同的(忘记提及我的问题),但它会抛出同样的错误? btw在查询中有一个聚合函数MAX()? – red

+0

@red您是否尝试过我给出的查询 –