我不知道什麼是你的目標,但這裏是一些樣品:
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循環結果,並獲得應該顯示的用戶列表,並獲取從數據庫只有適合自己的,有時這會更快的信息,嘗試基準所有變體
你能提供的樣本數據和預期的效果? – sgeddes
@sgeddes我剛剛編輯我的問題,使其更簡單,更清晰。 –