SELECT `bio_community_events`.`id`,
`bio_community_events`.`begin_on`,
`bio_community_events`.`name`
FROM `bio_community_events`
JOIN `bio_contacts`
ON (`bio_contacts`.`contact_id` = `bio_community_events`.`user_id`)
WHERE `bio_contacts`.`user_id` = '33'
UNION ALL --- or UNION if this gives you
--- duplicate row
SELECT `bio_community_events`.`id`,
`bio_community_events`.`begin_on`,
`bio_community_events`.`name`
FROM `bio_community_events`
JOIN `bio_contacts`
ON (`bio_contacts`.`user_id` = `bio_community_events`.`user_id`)
WHERE `bio_contacts`.`contact_id` = '33'
或像這樣:
SELECT `bio_community_events`.`id`,
`bio_community_events`.`begin_on`,
`bio_community_events`.`name`
FROM `bio_community_events`
JOIN
(SELECT `bio_contacts`.`contact_id` AS id
FROM `bio_contacts`
WHERE `bio_contacts`.`user_id` = '33'
UNION ALL
SELECT `bio_contacts`.`user_id` AS id
FROM `bio_contacts`
WHERE `bio_contacts`.`contact_id` = '33'
) AS un
ON (un.id = `bio_community_events`.`user_id`)
要以限制設置爲所有示例#1中返回的行使用:
(SELECT ...)
UNION ALL
(SELECT ...)
ORDER BY ? --- optional
LIMIT x ;
使用ORDER BY
在這樣的查詢中可能會非常昂貴。你也可以有這樣的(不同的)查詢,可以使用索引:
(SELECT ...
ORDER BY ?
LIMIT a
)
UNION ALL
(SELECT ...
ORDER BY ?
LIMIT b
)
LIMIT x ; --- with or without this LIMIT
另一種方式來解決原來的問題是使用EXISTS
:
SELECT `bio_community_events`.`id`,
`bio_community_events`.`begin_on`,
`bio_community_events`.`name`
FROM `bio_community_events`
WHERE EXISTS
(SELECT *
FROM `bio_contacts`
WHERE `bio_contacts`.`user_id` = '33'
AND `bio_contacts`.`contact_id` = `bio_community_events`.`user_id`
)
OR EXISTS
(SELECT *
FROM `bio_contacts`
WHERE `bio_contacts`.`contact_id` = '33'
AND `bio_contacts`.`user_id` = `bio_community_events`.`user_id`
)
或:
SELECT `bio_community_events`.`id`,
`bio_community_events`.`begin_on`,
`bio_community_events`.`name`
FROM `bio_community_events`
WHERE EXISTS
(SELECT *
FROM `bio_contacts`
WHERE (`bio_contacts`.`user_id` = '33'
AND `bio_contacts`.`contact_id` = `bio_community_events`.`user_id`)
OR (`bio_contacts`.`contact_id` = '33'
AND `bio_contacts`.`user_id` = `bio_community_events`.`user_id`)
)
如果您的計劃是要fi找到最有效的查詢,嘗試所有正確工作(使用IN,使用UNION,使用EXISTS) - 添加您想要偏離的ORDER BY
- 並檢查其速度和執行計劃。
我至少具有:
在表
字段(一個或多個)上user_id
的索引的索引和
- 表
bio_contacts
,兩個複合指標
- 上
(contact_id, user_id)
和
- 上
(user_id, contact_id)
和POST另外一個問題,如果你不能讓它在小於X毫秒運行( X由你的老闆決定:)
你爲什麼要關注事件的創造者,而不是事件記錄器d本身? –
像'SELECT ... FROM bio_contacts'? – daGrevis