如何使用3个表的连接计算列数据

时间:2017-04-18 07:59:13

标签: php mysql database

我有三张桌子

tbl_product 
item_id | item_name

company_details
v_id | item_id | company_name

user_ratings 
r_id | rate | v_id 

我想计算费率并获得公司的费率。这是我的查询

SELECT  company_details.v_id,
        company_details.company_name,
        COUNT(user_ratings.rate) as vote,
        user_ratings.rate,
        tbl_product.item_name
FROM    company_details
LEFT JOIN tbl_product ON tbl_product.item_id = company_details.item_id
LEFT JOIN user_ratings ON user_ratings.v_id = company_details.v_id
GROUP BY company_details.v_id, user_ratings.rate

这是我正在追查此查询后的信息:

v_id  company_name           vote  rate  item_name  
1     The Oberoi Udaivilas   1     4     5 Star Hotels  
1     The Oberoi Udaivilas   1     5     5 Star Hotels  
2     The Taj Mahal Palace   2     5     4 Star Hotels  
3     Rambagh Palace         1     5     3 Star Hotels  
4     Taj Lake Palace        1     5     5 Star Hotels  
5     Windflower Hall        1     3     2 Star Hotels  
5     Windflower Hall        1     5     2 Star Hotels  
6     Leela Palace Kempinski 0     n     4 Star Hotels  
7     Umaid Bhawan Palace    0     n     4 Star Hotels  
8     Hotel Ratan Vilas      0     n     4 Star Hotels  
9     The Leela Palace       0     n     4 Star Hotels  
10    The Imperial Hotel     0     n     3 Star Hotels  

您可以看到投票栏没有计算。

这就是我所期待的

v_id  company_name          vote  rate  item_name   
1     The Oberoi Udaivilas  2     5     5 Star Hotels   
2     The Taj Mahal Palace  2     5     4 Star Hotels   

但是这个查询不计算来自user_ratings表的速率,因为我也希望得到速率,如果我从user_ratings.rate子句中删除select,那么这个查询有效,但是当我在user_ratings.rate子句中添加select时,此查询不会将费率计为(投票),并且每次计数都会返回一行。

4 个答案:

答案 0 :(得分:1)

您应该从group by子句中删除 user_ratings.rate 并添加 tbl_product.item_name

SELECT
    company_details.v_id,
    company_details.company_name,
    tbl_product.item_name,
    COUNT(user_ratings.rate) as vote,
    avg(user_ratings.rate) as rate
FROM
    company_details
    LEFT JOIN tbl_product ON tbl_product.item_id = company_details.item_id
    LEFT JOIN user_ratings ON user_ratings.v_id = company_details.v_id
GROUP BY company_details.v_id, company_details.company_name, tbl_product.item_name;

答案 1 :(得分:0)

在我看来,您的查询只缺少rate列上的汇总,而且从预期的输出中我会说它是max。您还应该修复group by。试试这个

SELECT  company_details.v_id,
        company_details.company_name,
        COUNT(user_ratings.rate) as vote,
        MAX(user_ratings.rate) as rate,
        tbl_product.item_name
FROM    company_details
LEFT JOIN tbl_product ON tbl_product.item_id = company_details.item_id
LEFT JOIN user_ratings ON user_ratings.v_id = company_details.v_id
GROUP BY company_details.v_id,
         company_details.company_name,
         tbl_product.item_name

答案 2 :(得分:0)

查询和结果都是正确的。查看费率

答案 3 :(得分:0)

您可以尝试此查询,它将根据您给定的3个表格返回您的确切输出。

"select c.v_id , c.company_name , u.rate , p.item_name from company_details c  join  tbl_product p on p.item_id = c.item_id  join user_details u on c.v_id = u.v_id group by c.company_name ";