[英]mysql return same rows union
在我的數據庫中,我有類別,報價和優惠券。 我想計算每個類別中存在的優惠和優惠券。 當我使用工會時,它兩次返回相同的類別。 我有以下查詢,返回相同名稱的相同類別行。 我嘗試使用工會不同,但它不起作用。
(SELECT
cat1.id AS cat1id, cat1.title AS title,
count(offers.id) AS offercounter
FROM cat1
INNER JOIN offers
ON offers.category=cat1.title
GROUP BY cat1.id
order by cat1.order)
UNION
(SELECT
cat1.id AS cat1id, cat1.title AS title,
count(coupons.id) AS couponscounter
FROM cat1
INNER JOIN coupons
ON coupons.category=cat1.title
GROUP BY cat1.id
order by cat1.order)
結果
cat1id title offercounter
2 Food 5388
23 Clothes 6000(this is offers)
32 Technology 499
40 Clothes 4(this is coupons)
我想買衣服(要價+優惠券)。 示例:衣服= 6004,而不是兩行不同
理想的結果將是:
cat1id title offercounter
2 Food 5388
23 Clothes 6004(offers+coupons)
32 Technology 499
聯合返回不同的行。 您返回的行確實是不同的。 工會后,您需要做的就是獲得合乎需要的結果。
select min(cat1id) as cat1id, title, sum(offercounter) as offercounter
from
(your_query) as subquery
group by title
用現有查詢替換your_query
另一種避免合並或子查詢的方法是使用幾個LEFT OUTER JOINS,並計算每個表中不同的ID:
SELECT cat1.id AS cat1id,
cat1.title AS title,
COUNT(DISTINCT offers.id) + COUNT(DISTINCT coupons.id) AS offercounter
FROM cat1
LEFT OUTER JOIN offers ON offers.category = cat1.title
LEFT OUTER JOIN coupons ON coupons.category = cat1.title
GROUP BY cat1.id AS cat1id,
cat1.title AS title
編輯
當沒有匹配的行時,左外部聯接將返回空行。
例如,如果cat1上有一行,商品上有匹配行,但優惠券上沒有匹配行,則結果行將由cat1中的行,優惠中的行和優惠券中的字段組成。
此SQL將獲取匹配行的所有組合。 因此,如果您有:-
cat1 fields offers fields coupons fields
id title id category id category
1 fred 99 fred 77 fred
1 fred 99 fred 88 fred
1 fred 100 fred 77 fred
1 fred 100 fred 88 fred
2 burt 120 fred NULL NULL
2 burt 121 fred NULL NULL
因此,計數使用DISTINCT只能將一個類別中的每個ID一次。 由於COUNT(字段名稱)僅計算非空值,因此在此示例中,第二類別的數據來自優惠券的計數將為0。
您為什么不簡單地sum
出offercounter
並order by
cat1id
order by
使用group by
。
SELECT cat1id,title,sum(offercounter) as offercounter
FROM offers GROUP BY title ORDER BY cat1id
查看: SQL小提琴
輸出:
cat1id title offercounter
2 Food 5388
23 Clothes 6004
32 Technology 499
可能這會有所幫助。
SELECT cat1.id AS cat1id, cat1.title AS title ,((SELECT COUNT(offers.id) FROM offers WHERE offers.category=cat1.title)+(SELECT COUNT(coupons.id) FROM coupons WHERE coupons.category=cat1.title)) AS offercounter
FROM cat1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.