繁体   English   中英

从两个表中获取所有记录,但仅从第二个表中获取不在第一个表中的记录

[英]get all records from two tables but from second table only the ones that are not in first

我正在创建一个MUD游戏,因为我有两个任务表,其中有一个active_quests和completed_quests。 我的玩家可以看到很多自定义报告。

在一个这样的报告中,他们选择了一堆quest_id之后,我想向他们显示该任务的得分/状态。 该报告应确保我只想显示active_quests表中的分数(如果该表中存在分数),否则仅显示completed_quests的分数。

所以我需要的查询( 用伪代码 )是这样的:

select active_quests.*
from active_quests
where quest_id in (<list_of_quest_ids>)
and player_id = <player_id>

UNION

select completed_quests.*
from completed_quests
where quest_id NOT in (<the_results_we_got_above>)
and quest_id in (<list_of_quests>)
and player_id = <player_id>

但是我不知道该怎么写:(

假设您是像

  select quest_id from you_quest_table where your_col = your_val

你可以用类似的东西

    select active_quests.*
    from active_quests
    where quest_id in (
      select quest_id from you_quest_table where your_col = your_val
      )
    and player_id = <player_id>

    UNION

    select completed_quests.*
    from completed_quests
    where quest_id NOT in (

    select active_quests.*
    from active_quests
    where quest_id in (
      select quest_id from you_quest_table where your_col = your_val)
    and player_id = <player_id>

    )
    and quest_id in (
       select quest_id from you_quest_table where your_col = your_val
    )
    and player_id = <player_id>

使用左外部联接可保留左表中的所有记录以及右表中的匹配记录。

一种方法not exists

select aq.*
from active_quests aq
where aq.quest_id in (<list_of_quest_ids>) and
      aq.player_id = <player_id>
union all
select cq.*
from completed_quests
where not exists (select 1
                  from activequests aq
                  where aq.player_id = cq.player_id and
                        aq.quest_id = cq.quest_id
                 )
      cq.quest_id in (<list_of_quests>) and
      cq.player_id = <player_id>;

笔记:

  • 除非明确要删除重复项,否则请使用UNION ALL (这会降低性能)。
  • 在MySQL中,如果您使用的是相关逻辑,则无需在NOT EXISTS (或NOT INLEFT JOIN )逻辑中重复第一个查询。 在其他数据库中,CTE将简化整个过程。
  • 使用正确的索引编制,这应该很快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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