合并3个SQL表(一个需要搜索,一个平均,一个需要计数)

时间:2018-10-21 07:09:48

标签: mysql sql

这有点像个怪物查询,但我无法解决,但我有3个表共享一些我想从中获取并显示数据的通用ID,但不确定是否可能?

我的桌子:

Members

|MemberID | Fname | Lname
|  1      | foo   | barr
|  2      | bazz  | lorem
(PK MemberID)

MemberRatings

|RatingID | MemberID | RatingValue
|1        | 1        | 5.0
|2        | 1        | 4.4
|3        | 2        | 4.5
|4        | 1        | 4.0
(PK RatingID, FK MemberID-> Members MemberID

Rental

|RentalID | MemberID | RentalDate
|1        | 1        | 2018-06-06
|2        | 1        | 2018-08-08
(PK RentalID, FK MemberID->Members MemberID)

我的查询:

SELECT
    #member info
    m.MemberID, m.Fname, m.Lname,
    #ratings info (get ready to cast AVG as decimal)
    ra.RatingID, ra.MemberID, CAST(AVG(ra.RatingValue) AS DECIMAL(3,2)),
    #check how many rentals they have
    re.RentalID, re.MemberID
FROM
    #Member MemberID = Rating MemberID
    Members m 
LEFT JOIN 
    MemberRatings ra ON m.MemberID = ra.MemberID
    #Member MemberID = Rental memberID
LEFT JOIN 
    Rental re ON m.MemberID = re.MemberID
    #Where search terms match
WHERE 
    (m.Fname LIKE '%".$membersSearchTerm."%' OR 
     m.Lname LIKE '%".$membersSearchTerm."%')
#Group by memberID to do the AVG
GROUP BY 
    m.MemberID;

关闭到我想要的输出,但是拉出重复的列并返回NULL结果

输出:

| MemberID | Fname | Lname | RatingID | MemberID | CAST(AVG(ra.RatingValue) AS DECIMAL(3,2)) | RentalID | MemberID 
| 1        | foo   | barr  | 1        | 1        | 4.46 | 1    | 1
| 2        | bazz  | lorem | 2        | 2        | 4.5  | NULL | NULL

感觉我联接不正确,但是我对SQL的了解非常有限,我试图通过LEFT JOIN来做到这一点,是否有更好的方法将结果输出为这样的东西:

| MemberID | Fname | Lname | AVG  | Rentals |
| 1        | foo   | barr  | 4.46 | 2       | 
| 2        | bazz  | lorem | 4.5  | 0       | 

我很累在RentalID = NOT NULL中添加一个WHERE,但这也不能完全解决问题。

1 个答案:

答案 0 :(得分:2)

  • 执行Group By时,需要确保您的“选择”列表仅包含聚合的列(例如:最小值,最大值,平均值,计数等)和/或正在被的列>分组

阅读:SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

  • 要计算会员的租金总数,您需要使用COUNT()函数。

尝试以下操作:

SELECT
  m.MemberID, 
  m.Fname, 
  m.Lname,
  CAST(AVG(ra.RatingValue) AS DECIMAL(3,2)) AS average_rating,
  COUNT(DISTINCT re.RentalID) AS rental_count 
FROM Members m 
LEFT JOIN MemberRatings ra 
       ON m.MemberID = ra.MemberID
LEFT JOIN Rental re 
       ON m.MemberID = re.MemberID
WHERE (
  m.Fname LIKE '%".$membersSearchTerm."%' OR
  m.Lname LIKE '%".$membersSearchTerm."%'
)
GROUP BY m.MemberID, 
         m.Fname, 
         m.Lname