2013-06-12 60 views
-3

我們有兩個表。關於每個用戶的收藏作者的sql查詢

1. information 

title body  name 

title1 body1 author1 
title2 body2 author1  
title1 body1 author2 
title1 body1 author3 

2. interactions 

name  favorited user_favorited_by 

author1  yes   user1 
author2  yes   user1 
author1  yes   user2 
author1  no   user3 

問題是:誰爲每個用戶最喜歡的作者?

查詢應該給我們基於示例如下回答:

user1 author1 
user1 author2 
user2 author1 

任何幫助表示讚賞。

+0

兩點減號?爲什麼?你可以在這裏發表評論。我認爲問題很清楚! – stefanosn

回答

1

這裏是一個連接的作品:

SELECT DISTINCT user_favorited_by, a.name 
    FROM information a 
    JOIN interactions b 
    ON a.name = b.name 
WHERE favorited = 'yes' 

既然你只有 '名' 來加入,您需要DISTINCT,或者您可以通過GROUP BY選定的字段從輸出中刪除重複的行。

這裏是演示:SQL Fiddle

0

可能,我建議:

select user_favorited_by, author from information a 
inner join interaction b on a.name = b.name 
where b.favorited = 'yes' 
0

我認爲有以下應該工作

SELECT DISTINCT user_favorited_by, 
       a.name 
    FROM information a, 
     interactions b 
WHERE a.name = b.name 
    AND favorited = 'yes' 
+1

雖然這當然有效,但我不會鼓勵人們使用舊式連接。 –