如何从Mysql

时间:2017-05-30 13:34:45

标签: mysql mysqli

我有两张表,如下,

Table 1 : 

Id  User_id  rating1  rating2 rating3 

1     4       4         3      5 
2     4       5         2      2
3     1       5         5      5
4     4       1         2      3 


Table 2 : 

Id  User  rating1   rating2  rating3 comment 
1    1      5          2          1   okay
2    4      2          4          4   good

我希望得到的rating_id的计数为rating1,其值为1,2,3,4,5,其中rating2的值介于1,2,3,4,5之间,且rating3的值介于1,2之间, 3,4,5

我正在尝试以下方式,

select count(Table1.User_id) 
from Table1
join Table2
  on Table1.User_id = Table2.User 
where Table1.rating1  = ( 1 || 2 || 3 || 4 || 5)  
  and Table2.rating1 = ( 1 || 2 || 3 || 4 || 5 )

但它不起作用。请任何人帮助我

2 个答案:

答案 0 :(得分:0)

根据您的评论,您的查询与您的愿望结果相差甚远。

您需要将表格转换为单列

SELECT rating, count(*)
FROM (
      SELECT `User_id` , `rating1` as rating FROM Table1
      UNION ALL
      SELECT `User_id` , `rating2` as rating FROM Table1
      UNION ALL
      SELECT `User_id` , `rating3` as rating FROM Table1
      UNION ALL
      SELECT `User`    , `rating1` as rating FROM Table2
      UNION ALL
      SELECT `User`    , `rating2` as rating FROM Table2
      UNION ALL
      SELECT `User`    , `rating3` as rating FROM Table2
   ) as combine
GROUP BY rating
ORDER BY rating

答案 1 :(得分:0)

使用IN(1,2,3,4,5)Insted of =(1,2,3,4,5)

它会给出多个oprands的错误,因为在比较一对一的值时可以使用相同的值。

SELECT t1.user_id,t2.user,count(*) as Count_Rate
FROM 
(SELECT * FROM table1 WHERE rating1 IN ('1','2','3','4','5')) as t1
JOIN 
(SELECT * FROM table2 WHERE rating1 IN ('1','2','3','4','5')) as t2
on t1.user_id = t2.user
GROUP by user_id

或者您也可以通过添加

来尝试
(SELECT *,count(rating1='1') AS rate1 FROM table1 WHERE rating1 IN ('1','2','3','4','5')) as t1

希望这有助于