1

我有一个查询

SELECT 
  count(product) as amount,
  product, 
  sum(price) AS price 
FROM `products` 
WHERE 
  brid = 'broker' 
AND 
  cancelled is null 
GROUP BY product 
WITH ROLLUP

是否可以查询一个表以获取代理 ID,然后为每个代理运行上面写为 1 个查询的查询?

几乎像:

SELECT brid FROM membership
THEN

SELECT 
  count(product) as amount,
  product, 
  sum(price) AS price 
FROM `products` 
WHERE 
  brid = membership.brid 
AND 
  cancelled is null 
GROUP BY product 
WITH ROLLUP

THEN
SELECT NEXT brid

这可能吗?我知道如何在 PHP 中做到这一点,但我更喜欢 1 个可以创建数组的查询,而不是每个查询的大量查询。

谢谢亚当。

4

3 回答 3

3

当然,您可以对“brid”字段和“product”字段进行分组。如下所述,WITH ROLLUP将导致它先按“brid”排序,然后按“product”排序:

SELECT
  brid, 
  count(product) as amount,
  product, 
  sum(price) AS price 
FROM `products` 
WHERE 
  brid IN (SELECT brid FROM membership)
AND 
  cancelled is null 
GROUP BY brid, product 
WITH ROLLUP
于 2012-09-21T13:49:16.300 回答
0
SELECT 
  count(product) as amount,
  product, 
  sum(price) AS price 
FROM `products` 
INNER JOIN membership on membership.brid = products.brid
WHERE 
  cancelled is null 
GROUP BY product 
WITH ROLLUP
于 2012-09-21T13:49:11.330 回答
0

据我从您的示例中可以理解,您所需要的只是inner join between membership and products on brid

举个例子:

products桌子:

CREATE TABLE `test` (
  `price` int(11) DEFAULT NULL,
  `product` varchar(20) DEFAULT NULL,
  `brid` varchar(20) DEFAULT NULL,
  `cancelled` varchar(20) DEFAULT NULL
) 

membership桌子:

CREATE TABLE `membership` (
  `brid` varchar(20) DEFAULT NULL
) 

以下是我query的要求:

SELECT 
  t.brid, count(t.product) as amount,
  t.product, 
  sum(t.price) AS price 
FROM products t, membership m
WHERE 
  t.brid = m.`brid`
AND 
  cancelled is null 
GROUP BY product 

希望有帮助!

于 2012-09-21T13:55:36.920 回答