簡體   English   中英

使用 mysql 獲取單個商店的平均評分

[英]Get average rating for individual shop using mysql

我正在加入兩個表,即帶有評級表的商店表,並希望獲取具有單個商店評級的所有商店列表,我對此進行了書面查詢,但在輸出中僅獲取那些在評級表中有評級的商店,但我想要如果商店不t 有評級然后顯示 0 否則按表記錄顯示。

商店表:-

id  shop name      
  1     shop_1      
  2     shop_2      
  3     shop_3      
  4     shop_4

評分表

id  shop_id  rating      
  1     1      3      
  2     4      2

詢問:

$this->db->select('shop.*,shop.id as shop_id');
    $this->db->select('COALESCE(ROUND(AVG(rat.rating),1),0) as avgRate');
    $this->db->from('shop');
    $this->db->join('rating_reviews as rat', 'rat.shop=shop.id', 'left');
    $this->db->get()->result_array();

電流輸出:

  id  shop_id      avgRate       
   1     1            3      
   2     4            2 

預期輸出:

 id  shop_id      avgRate     
   1     1            3     
   2     2            0           //(no rating given for this shop)    
   3     3            0           //(no rating given for this shop)       
   4     4            2 

聚合函數

您遇到錯誤的原因是功能類似於AVG | COUNT AVG | COUNT聚合函數,也就是說它們聚合所有數據並通常輸出單個記錄/結果。

例如:

  • 假設您有一個以id為主鍵的桌子shops
  • 表中有35家店鋪
  • 主鍵沒有中斷(例如從 1 到 35)

以下查詢將返回1行/結果:

# Query                          # Output:  # FIELD_1 # FIELD_2 (second statement)
SELECT COUNT(shop.id) FROM shop             # 35
SELECT shop.id, COUNT(shop.id) FROM shop    # 1       # 35

以上兩個語句都將返回1結果。 第一個只是商店數量的count35 ),第二個將額外輸出第一個商店的id1 )。

您的查詢功能基於相同的原則,例如COUNT AVG函數是一個聚合函數,將從查詢中返回1結果/行。

SELECT 
    shop.*, shop.id as shop_id,
    COALESCE(ROUND(AVG(rat.rating),1),0) as avgRate
FROM shop
    LEFT JOIN rating_reviews AS rat ON rat.shop=shop.id

-- Outputs: All fields from `shop` for the first shop followed by [shop_id] and [avgRate]
-- For example...
# shop.id # shop.name # shop.type   # shop_id # avgRate
# 1       # Tesco     # Supermarket # 1       # 3.5

然而,有兩種方法可以規避這種行為:

使用GROUP BY

SELECT i, AVG(...) AS a FROM ... LEFT JOIN ... GROUP BY i

嵌套的SELECT語句

SELECT i, (SELECT AVG(...) FROM ... WHERE ...) AS a FROM ...

通過...分組

SELECT 
    shop.*, shop.id as shop_id,
    COALESCE(ROUND(AVG(rat.rating),1),0) as avgRate
FROM shop
    LEFT JOIN rating_reviews AS rat ON rat.shop=shop.id
GROUP BY shop.id

嵌套選擇

SELECT
    shop.*, shop.id as shop_id,
    (SELECT
         COALESCE(ROUND(AVG(rat.rating),1),0)
     FROM rating_reviews as rat
     WHERE rat.shop=shop.id
    ) as avgRate
FROM shop

我想建議另一種方法,完全避免加入:

select
  distinct id,
  (
     select coalesce(round(avg(rat.rating), 1), 0)
     from rating_reviews as rat where shop.id=rat.shop
  ) as avgRate
from shop

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM