多个WHERE子句查询不起作用

时间:2013-10-10 00:45:44

标签: sql join

编辑:我编辑了这个问题。

在这里, $ id = $ _SESSION ['id'] ,让我们说$ id = 1(保罗)。

活动

 sender   recipient      type 

  1           2          message
  2           4          like

USERS

 id       firstname   
  1         paul   
  2         anna   

CONNECTION

 subscribing  subscribed
     1            2

这就是我现在所处的位置:

 SELECT events.sender, events.recipient, events.type, users.firstname, users.lastname,
 connection.subscribing, connection.subscribed   
 FROM events, users, connection
 WHERE events.sender=users.id
 AND connection.subscribing =$id`

此查询的目标是加入来自用户2(Anna)的事件和信息,因为用户1(Paul)订阅了她的Feed (在连接列表中)。用户1应该只看到他订阅的用户的事件+信息(此处仅限Anna)

我的当前查询不起作用,原因如下:

1)行重复

2)无论$ id的值如何,表events中的所有行都会显示:过滤器  不起作用。

任何想法如何解决?

2 个答案:

答案 0 :(得分:1)

我不确定你的目标是什么,但这里有一些样本:

SELECT u.id, u.firstname, sender, recipient, post_id, type
FROM events e
    inner join users u
        ON (e.sender = $id) -- why you need additional table there?
    inner join post_list p
        ON (e.post_id = p.post_id)

另一个例子:

SELECT u.id, u.firstname, sender, recipient, post_id, type
FROM events e, users u, connection c, post_list p
where
    e.sender=u.id AND
    e.post_id=p.post_id AND
    u.id=c.subscribed AND
    u.id=$id

上一个任务将返回所有表的Cartesian product并“仅过滤”正确的表,您可以使用JOIN语法安全地替换上面的查询(注意表顺序):

SELECT u.id, u.firstname, sender, recipient, post_id, type
FROM events e
    inner join post_list p
        ON (e.post_id = p.post_id)
    inner join users u
        ON (e.sender = u.id AND u.id=$id)
    inner join connection c
        on (u.id = c.subscribed)

----更新

这是正确的查询:

select u.id, u.firstname, e.sender, e.recipient, e.type
from users u inner join events e on (u.id=.e.sender) -- this query return ALL events
-- next part "filters" results
where
u.id in (select subscribed from connection where subscribing=$id)

您也可以在ON子句中移动过滤条件

select u.id, u.firstname, e.sender, e.recipient, e.type
from users u inner join events e on (u.id=.e.sender and u.id in (
select subscribed from connection where subscribing=$id))

出于性能原因,我建议使用另一种变体:

select e.* from events e
where e.sender in (select c.subscribing from connection c where c.subscribed=$id)

此查询返回所有事件,没有用户的信息。所有用户都应存储在memcache中(例如),在输出到页面时,您可以添加用户名,头像等

另外,你可以通过php循环结果并获取应该显示的用户列表,并仅为他们从db获取信息,有时这会更快,尝试对所有变体进行基准测试

答案 1 :(得分:1)

如果我正确理解你的问题和表格模式,这应该适合你:

select u.id, u.firstname, 
    e.sender, e.recipient, e.post_id, e.type, 
    pl.post
from events e 
    join users u on e.sender != u.id
    join connection c on c.subscribed = e.sender 
    join post_list pl on e.post_id = pl.post_id
where e.sender = $id

我并不完全理解您的事件与用户之间的关系,但这应该让您朝着正确的方向前进。