2012-02-29 64 views
0

我有一個應用程序,非常基本的描述:PHP MySQL的加入存在

  1. 用戶登錄 - >他們發佈「活動」(如滑雪)
  2. 用戶有朋友
  3. 用戶可以綁定多個朋友活動
  4. 用戶可以「喜歡」的朋友

我需要的是一個查詢,以檢查是否允許用戶「喜歡」的創建活動他們的一位朋友的活動。只有當其中一個用戶朋友被綁定到目標活動時,才允許它們。

users: id, name 
usersFriends: id, uid, friendUid 
activities: id, description 
activitiesUsers: id, activityId, uid 
activitiesLikes: id, activityId, uid 

我希望有人能幫助我這個查詢,並且如果可能的話返回true或false。我希望我的問題是清楚的,並感謝您的時間:)

+2

故事中有三個不同的用戶/朋友。例如,請標註他們的A,B和C,因爲這是開放的多種解釋。 – CodeCaster 2012-02-29 18:42:34

+0

我希望現在清楚;) – randomKek 2012-02-29 18:45:34

+1

我會*仍然*清理你的變量,並通過獨特的名稱來調用它們,所以稍後混淆不清,所以id變成'userid',或'friendid',或'activityid'等;這不僅使它變得清潔,而且爲以後的JOINS澄清了隱含關係。 – Jakub 2012-02-29 18:47:40

回答

1

這應該產生爲所有用戶的朋友列表activities.id

SELECT 
    activities.id AS canLikeId 
FROM 
    users u 
    JOIN usersFriends uf ON u.id = uf.uid 
    JOIN activitiesUsers au ON uf.friendId = au.uid 
    JOIN activities a ON a.id = au.activityId 

包裹在EXISTS,它看起來像:

SELECT activities.id FROM activities aCanLike 
WHERE EXISTS (
    SELECT 
     a.id AS canLikeId 
    FROM 
     users u 
     JOIN usersFriends uf ON u.id = uf.uid 
     JOIN activitiesUsers au ON uf.friendId = au.uid 
     JOIN activities a ON a.id = au.activityId 
    WHERE a.id = aCanLike.id 
) 

或者一些與試圖獲取一切從activities通過任何用戶的朋友所擁有的IN()條款。

SELECT 
    activities.* 
FROM activities JOIN activitiesUsers ON activities.id = activitiesUsers.activityId 
WHERE activitiesUsers.uid IN (
    SELECT friendUid FROM usersFriends WHERE uid = $userid 
) 
1

假設你知道在查詢時用戶的ID和活動ID,你可以這樣做:

SELECT COUNT(*) FROM activitiesUsers WHERE activityId = 'xx' AND uid IN (SELECT friendUid FROM usersFriends WHERE uid = 'xx') 

應該返回0,如果沒有他們的朋友都綁定到活動或如果他們有朋友綁定到該活動正數......

+0

在某些情況下,我喜歡子查詢,這是一個。這個查詢應該工作。請參閱關於連接與子查詢的文章。 http://www.codersrevolution.com/index.cfm/2008/7/31/MySQL-performance-INNER-JOIN-vs-subselect – mozillanerd 2012-02-29 19:45:04

+0

@mozillanerd:你鏈接的文章顯示,subselect替代方法比join要慢得多一。 – 2012-03-01 01:44:36

1

這應做到:

select 
    count(*) as CanLike -- 0 if false, >= 1 if true 
from 
    usersFriends uf 
join 
    activitiesUsers au 
on 
    uf.friendUid = au.uid 
where 
    au.id = $activityId 
and 
    uf.uid = $userId 
1
SELECT COUNT(*) AS allowed 
FROM userFriends 
JOIN activitiesUsers ON (userFriends.uid = activitiesUsers.uid 
    AND activitiesUsers.activityId = $activity_id) 
WHERE userFriends.uid = $user_id