开发者

Is There Any Way to Combine These Queries into One?

I have two queries. I didn't knew how to make the same effect with only one. I'开发者_运维问答m not os good with SQL...

Here are pseudo-code:

friends = query("
    SELECT `bio_contacts`.`contact_id`
    FROM `bio_contacts`
    WHERE `bio_contacts`.`user_id` = '33'
")

query("
    SELECT `bio_community_events`.`id`, `bio_community_events`.`begin_on`, `bio_community_events`.`name`
    FROM `bio_community_events`
    WHERE `bio_community_events`.`user_id` IN friends
")

Is there any way to combine them into one query? It should improve performance, I guess. With joins, maybe?


SELECT `bio_community_events`.`id`, `bio_community_events`.`begin_on`, `bio_community_events`.`name`
FROM `bio_contacts` 
LEFT JOIN `bio_community_events` 
ON `bio_contacts`.`contact_id`= `bio_community_events`.`user_id`
WHERE `bio_contacts`.`user_id` = '33'


Your query does not even need a join. You could just say:

SELECT bio_community_events.id, bio_community_events.begin_on, bio_community_events.name FROM bio_community_events WHERE bio_community_events.user_id=33;

Or -- are your field names a bit off, and should we join the following fields: bio_contacts.contact_id=bio_community_events.user_id ? In that case you can do the following join:

SELECT `bio_community_events`.`id`, `bio_community_events`.`begin_on`, `bio_community_events`.`name`
    FROM `bio_community_events` INNER JOIN `bio_contacts` on `bio_community_events`.user_id=bio_contacts.contact_id
WHERE bio_contacts.user_id=33;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜