【问题标题】:Selecting multiple entries for the same attribute being equal to another为同一属性选择多个条目等于另一个
【发布时间】:2020-05-24 22:05:25
【问题描述】:

我想修改我现有的 SQL 查询,但无法让它按我想要的方式工作。 (这与作业/考试无关)

我想要一个像现在一样获取所有地图 ID、地图名称和奖励积分的查询,但获取所有不同运行 ID 的地图,而不是只获取一次地图 ID。现在,如果 inf_times 中有用户的 mapid,它将不再显示在最终列表中。如果 mapid 不在该用户的 inf_times 中,我希望为每个 runid 显示一次地图。

表结构:

inf_maps: mapid, mapname
inf_simpleranks_maps: mapid, runid, rewardpoints
inf_times: uid, mapid, runid
select a.mapid, b.mapname, a.rewardpoints 
from (select r.mapid, rewardpoints 
      from inf_maps r, inf_simpleranks_maps srm 
      where r.mapid 
      not in (select mapid 
              from inf_times 
              where uid = %d 
              group by uid, mapid) 
      and r.mapid = srm.mapid 
      order by rewardpoints desc) a, 
inf_maps b 
where a.mapid = b.mapid;

示例

inf_times
uid mapid runid   
1    4     1

inf_simpleranks_maps
mapid runid rewardpoints
4       1       10
4       2       12 

inf_maps
mapid mapname
4      mapmap

查询应该返回

mapid mapname rewardpoints
4      mapmap     12

相反,它现在什么也不返回。

【问题讨论】:

    标签: mysql sql join select


    【解决方案1】:

    使用not exists 尝试以下操作。这是demo

    select
      im.mapid,
      im.mapname,
      ism.rewardpoints
    from inf_maps im
    join inf_simpleranks_maps ism
    on im.mapid = ism.mapid
    where not exists
    (
      select
        mapid
      from inf_times it
      where ism.mapid = it.mapid
      and ism.runid = it.runid
    )
    

    输出:

    | mapid | mapname | rewardpoints |
    | ----- | ------- | ------------ |
    | 4     | mapmap  | 12           |
    

    【讨论】:

    • 谢谢! SQL 的方式对我来说仍然是未知的,但这让一切变得更加清晰,希望我能够自己构建未来的查询
    【解决方案2】:

    你的解释很难理解。但是,根据您的示例数据,以下查询将产生您期望的结果:

    select  m.*, r.rewardpoints
    from inf_maps m
    inner join inf_simpleranks_maps r on r.mapid = m.mapid
    where not exists (
        select 1 from inf_times t where t.mapid = m.mapid and t.runid = r.runid
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 2021-10-31
      • 2015-12-03
      • 2020-12-09
      • 2014-09-25
      • 1970-01-01
      • 2017-01-29
      相关资源
      最近更新 更多