在一个查询中使用两个COUNT语句时出现未知列错误

时间:2018-07-03 20:05:23

标签: mysql sql

我正在尝试在一个SQL查询中运行2个不同的COUNT实例,但出现此错误:

  

未找到列:1054'on子句'中的未知列'po.product_id'

这是sql:

aspxGridView

3 个答案:

答案 0 :(得分:1)

GROUP BY中包含该列是不够的。您还需要将其包括在SELECT中:

SELECT product_id, COUNT(DISTINCT `outlet_id`) AS `outlets`
FROM `prod_outlets`
GROUP BY `product_id`

答案 1 :(得分:1)

如果要按列联接,则必须由SELECT语句返回。在您选择的列列表中包含product_id

更改:

INNER JOIN (SELECT COUNT(DISTINCT `outlet_id`) AS `outlets` FROM `prod_outlets` GROUP BY `product_id`) as `po` ON po.`product_id` = bbp.`prod_id`

收件人:

INNER JOIN (SELECT `product_id`, COUNT(DISTINCT `outlet_id`) AS `outlets` FROM `prod_outlets` GROUP BY `product_id`) as `po` ON po.`product_id` = bbp.`prod_id`

如果没有选择该列,则product_id在此中间表(此处称为po)之外不可见。这就是为什么出现错误未知列的原因,因为只有已知列是outlets

答案 2 :(得分:0)

为什么不直接加入

SELECT COUNT(*) vouchersleft, `prod_name`,
        `start_date`, 
        `end_date`,
        `reg_price`,
        `sale_price`,
        bbp.`prod_id`,
        `vouch_limits`,
        `sp_name`,
        `order_id`,
        `img_name`,
         COUNT(DISTINCT po.`outlet_id`) AS `outlets`
        FROM `vouchers` as `v`
        INNER JOIN `bb_products` as `bbp` ON bbp.`prod_id` = v.`product_id`
        INNER JOIN `service_providers` as `sp` ON sp.`service_provider_id` = bbp.`provider_id`
        INNER JOIN `prod_pics` as `pp` ON pp.`prod_id` = bbp.`prod_id`
        RIGHT JOIN `prod_outlets`  as `po` ON po.`product_id` = bbp.`prod_id`
        WHERE `frontend` = :frontend
        AND bbp.`featured` = :featured
        AND `order_id` = :order_id
        AND pp.`featured` = :featured_img
        GROUP BY bbp.`prod_id`