简体   繁体   中英

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM