SQL错过了什么..受影响的结果

时间:2014-03-06 19:01:36

标签: php mysql sql

我在MYSQLI中使用了这段代码:

SELECT da_brands.name AS brand_name,
    COUNT(da_deals.id) AS total_deals,
    0 AS total_downloaded_coupons,
    0 AS total_validated_coupons,
    COUNT(da_logs.id) AS total_likes
FROM da_brands, da_deals LEFT JOIN da_logs
    ON da_logs.fk_deal_id = da_deals.id
    AND da_logs.type = 'deal_like'
WHERE da_brands.fk_club_id = 6
    AND da_deals.fk_brand_id = da_brands.id
GROUP BY da_brands.name
ORDER BY da_brands.name ASC

结果:

brand_name  total_deals    total_downloaded_coupons   total_validated_coupons   otal_likes
Marca2      2              0                          0                         1
Marca1      12             0                          0                         4

应该是:

brand_name  total_deals    total_downloaded_coupons   total_validated_coupons   total_likes
Marca2      2              0                          0                         1
Marca1      9              0                          0                         4

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我相信你想要COUNT(DISTINCT da_deals.id) AS total_deals,,因为你只需要计算一次交易ID一次。

编辑:您的FROM语句是隐式内连接(逗号)和显式外连接的列表。我错过了。

你的查询应该像这样编写,包含所有显式连接:

SELECT da_brands.name AS brand_name,
    COUNT(DISTINCT da_deals.id) AS total_deals,
    0 AS total_downloaded_coupons,
    0 AS total_validated_coupons,
    COUNT(DISTINCT da_logs.id) AS total_likes
FROM da_brands
INNER JOIN da_deals
    ON da_deals.fk_brand_id = da_brands.id
LEFT JOIN da_logs
    ON da_logs.fk_deal_id = da_deals.id
    AND da_logs.type = 'deal_like'
WHERE da_brands.fk_club_id = 6
GROUP BY da_brands.name
ORDER BY da_brands.name ASC;

要显示品牌,即使他们缺少优惠和喜欢,请尝试这样的LEFT JOIN

SELECT da_brands.name AS brand_name,
    COUNT(DISTINCT da_deals.id) AS total_deals,
    0 AS total_downloaded_coupons,
    0 AS total_validated_coupons,
    COUNT(DISTINCT da_logs.id) AS total_likes
FROM da_brands
LEFT JOIN da_deals
    ON da_deals.fk_brand_id = da_brands.id
LEFT JOIN da_logs
    ON da_logs.fk_deal_id = da_deals.id
    AND da_logs.type = 'deal_like'
WHERE da_brands.fk_club_id = 6
GROUP BY da_brands.name
ORDER BY da_brands.name ASC;