繁体   English   中英

MySQL返回相同的行联合

[英]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。

您为什么不简单地sumoffercounterorder 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM