【问题标题】:Is There Any Way to Combine These Queries into One?有没有办法将这些查询合并为一个?
【发布时间】:2011-07-05 22:42:38
【问题描述】:

我有两个问题。我不知道如何只用一个来制作相同的效果。我不擅长 SQL...

以下是伪代码:

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
")

有没有办法将它们组合成一个查询?我猜它应该会提高性能。可能有连接?

【问题讨论】:

    标签: mysql sql optimization join


    【解决方案1】:
    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'
    

    【讨论】:

    • 是的,这行得通。但这也返回 3 个空行。有什么办法解决吗?
    • 给出空行的是左连接。您可能希望将其更改为内部联接。
    【解决方案2】:

    您的查询甚至不需要连接。 你可以说:

    选择bio_community_events.id, bio_community_events.begin_on, bio_community_events.name 来自bio_community_events 在哪里bio_community_events.user_id=33;

    或者 -- 您的字段名称是否有点偏离,我们是否应该加入以下字段: bio_contacts.contact_id=bio_community_events.user_id ?在这种情况下,你可以做 以下连接:

    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;
    

    【讨论】:

    • 宾果游戏!第二个查询是我需要的。
    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2022-11-24
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多