我有这个问题:
CREATE VIEW MOSTACTIVESELLER AS
Select a.* from
(
SELECT a.ownerID, b.sellerName, count(distinct a.ITEMID) as item_qty
FROM item AS a
INNER JOIN seller AS b ON a.ownerID = b.sellerID
GROUP BY a.ownerID,b.sellerName
) a
此视图查询的结果是:
+--ID--+--seller-+-qty--+
| 1000 | Nick | 3 |
| 1001 | Morgan | 2 |
| 1002 | stancly | 1 |
| 1003 | chandler | 1 |
| 1004 | chiptle | 3 |
| 1005 | samir | 2 |
| 1006 | matuidi | 3 |
| 1007 | medjek | 1 |
| 1008 | leo | 1 |
| 1009 | georgi | 1 |
| 1010 | bocheli | 2 |
+------+----------+---+
所以我想要的是使用像max这样的聚合函数来仅返回此列表中最活跃的卖家(仅1),因为你可以看到3个卖家有数量3,我认为max函数将返回一个。如果不是我可能会订购视图DESC并返回最高值。但无法使其发挥作用。我尝试使用max与视图MOSTACTIVESELLER我不知道该怎么做??
答案 0 :(得分:0)
我很惊讶你的查询在MySQL中运行 - 通常在视图的FROM
子句中不允许子查询。但这应该是一种观点:
CREATE VIEW MOSTACTIVESELLER AS
SELECT s.sellerID, s.sellerName, count(distinct i.ITEMID) as item_qty
FROM item i INNER JOIN
seller s
ON i.ownerID = s.sellerID
GROUP BY s.sellerID, s.sellerName
HAVING count(distinct i.ITEMID) = (SELECT count(distinct i.ITEMID)
FROM item i
GROUP BY i.ownerID
ORDER BY 1 DESC
LIMIT 1
);
编辑:
我认为LIMIT
允许使用=
,但MySQL对子查询中LIMIT
的使用有奇怪的限制。这很容易取代:
HAVING count(distinct i.ITEMID) >= ALL (SELECT count(distinct i.ITEMID)
FROM item i
GROUP BY i.ownerID
);