2012-02-28 68 views
-1

我有这个疑问:升级SQL查询加入

SELECT e.id AS event_id, e.title, e.date, e.category, e.place, 
      p.id, p.name, p.coor, p.nz, 
      a.user, a.event, COUNT(a.user) AS attending 
    FROM events AS e 
LEFT JOIN attendance a 
     ON a.event = e.id 
LEFT JOIN places p 
     ON p.id = e.place 
GROUP BY e.id, e.title 
ORDER BY attending DESC 

这个查询得到事件表事件,并加入一些其他表...(如果你能帮助我,使之比较有效,我会感谢你)

我叫另一个表:invited_friends:

event_id bigint(20)  
user_id int(11) 
owner tinyint(1) 

它存储邀请了certien事件。该用户ID(所有者是存储,如果用户是事件的创建者布尔)

我想仅在邀请当前用户时根据invite_friends表中的数据进行选择。

+0

INNER JOIN,它的工作,但不是所有的事件邀请的用户,他们中的一些公开给大家...所以它会无视他们:'code'INNER JOIN invited_friends我ON( i.event_id = e.id ) AND( i.user_id = 1439375286 )'code' – Amir 2012-02-28 18:32:12

+0

你怎么知道什么事件是公开的吗?存储在哪里? – Tobsey 2012-02-28 18:37:55

+0

如果e.category = 4,那么它是一个私人事件,当我使用内部连接像我显示它只是忽略旁边的邀请朋友的每个事件。 – Amir 2012-02-28 18:40:26

回答

0

我不是太熟悉MySQL,但这里有云:

SELECT e.id AS event_id, e.title, e.date, e.category, e.place, 
     p.id, p.name, p.coor, p.nz, 
     a.user, a.event, COUNT(a.user) AS 
FROM 
    events AS e 
    LEFT JOIN attendance a ON a.event = e.id 
    LEFT JOIN places p ON p.id = e.place 
WHERE 
    e.Category <> 4 
OR EXISTS (SELECT 
       NULL 
      FROM 
       invited_friends 
      WHERE 
       invited_friends.event_id = e.id 
      AND invited_friends.user_id = @username -- User to search for 
      ) 
GROUP BY 
    e.id, 
    e.title 
ORDER BY 
    attending DESC