2012-09-21 157 views
1

我有一個查詢mysql查詢子查詢循環?

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查詢可以創建一個數組而不是每個查詢噸。

謝謝 亞當。

回答

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 
3

當然,您可以GROUP BY「brid」字段和「product」字段。如下文所述,WITH ROLLUP將導致其由「布里德」進行排序,然後通過「產品」:

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 
+0

在PhpMyAdmin中測試並得到---#1221 - 錯誤地使用了CUBE/ROLLUP和ORDER BY –

+1

你是對的,'WITH ROLLUP'排除了'ORDER BY'的使用並且已經爲你排序 - 所以你可以跳過ORDER BY子句。更新。 – PinnyM

+0

謝謝!現在正常工作! –

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 

希望幫助!