2013-10-10 52 views
0

編輯:我已經編輯了這個問題。多個WHERE子句查詢不起作用

這裏,$ id = $ _SESSION ['id']並且讓我們說$ id = 1(Paul)。

活動

sender recipient  type 

    1   2   message 
    2   4   like 

USERS

id  firstname 
    1   paul 
    2   anna 

連接

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` 

此查詢的目標是由於用戶1(Paul)訂閱了她的訂閱源(在連接列表中),所以此訂戶的用戶2(Anna)的JOIN事件和信息爲。用戶1應該只看到來自用戶的事件+信息他已訂閱(這裏,安娜只)

當前查詢不起作用,原因如下:

1)行是重複

2)無論$ id的值如何,來自表events的所有行都顯示出來:過濾器 不起作用。

任何想法如何解決它?

+0

你能提供的樣本數據和預期的效果? – sgeddes

+0

@sgeddes我剛剛編輯我的問題,使其更簡單,更清晰。 –

回答

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) 

---- UPDATE

這裏是正確的查詢:

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循環結果,並獲得應該顯示的用戶列表,並獲取從數據庫只有適合自己的,有時這會更快的信息,嘗試基準所有變體

+0

+1,我編輯了我的問題,因爲我意識到我沒有解釋得很好。如果你能看一看就會很棒。 –

+0

@ChHr檢查更新的答案 –

+0

非常好的答案,謝謝你的明確解釋。現在就像一個魅力! –

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 

我不正確理解你與事件和用戶之間的關係,但這應該讓你朝着正確的方向前進。

+0

+1,我編輯了我的問題,因爲我意識到我沒有解釋得很好。如果你能看一看就會很棒。 –