2017-05-30 94 views
-2

我有一個像下面兩個表,如何從兩個表中獲取的記錄數在MySQL

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 

我想有1,2 3 4間,額定值1值誰USER_ID的計數, 5和1之間有誰rating2值,2,3,4,5和1之間有誰rating3值,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) 

但它不工作。請任何人幫我

+0

什麼意思*但是,它不工作*?任何錯誤消息或意外結果? – Jens

+0

意外的結果如沒有找到記錄 – Nisanth

+0

嘗試使用'in(1,2,3,4,5)'istead of'=(1 || 2 || 3 || 4 || 5)' – Jens

回答

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 
+0

感謝您的回答,但它顯示的只是整體計數 – Nisanth

+0

好的,讓我再檢查一次。 –

0

使用IN(1,2,3,4,5)=的insted的(1,2,3,4,5)

它會給出多個oprands的錯誤,因爲當比較一個值時可以使用equal。

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 

希望這有助於

相關問題