示例表如下:

SCENARIO_NATIONS
[scenID]  [side]  [nation]

scen001     1     Germany
scen001     2     Britain
scen001     2     Canada

SCENARIO_NEEDUNITS
[scenID]  [unitID]

scen001    0001
scen001    0003
scen001    0107
scen001    0258
scen001    0759

UNIT_BASIC_DATA
[unitID]  [nation]  [name]

  0001    Germany   Mortars
  0003    Germany   Infantry
  0107    Britain   Lt
  0258    Britain   Infantry
  0759    Canada    Kilted Yaksmen

目标:给定scenID,从数据库中提取按side, nation, name排序的单位列表。
我可以做任何事情,除了side包括:
SELECT scenario_needunits.scenID, unit_basic_data.nation, unit_basic_data.name
FROM scenario_needunits
LEFT OUTER JOIN unit_basic_data
ON scenario_needunits.unitID=unit_basic_data.unitID
WHERE scenario_needunits.scenID='scen001'
ORDER BY unit_basic_data.nation ASC, unit_basic_data.name ASC

我试过把SCENARIO_NATIONS表作为LEFT OUTER JOIN放到scenID上,但结果是所有单元都返回side1值,因为这始终是scenID表中SCENARIO_NATIONS的第一面。
从概念上讲,我认为需要发生的是SCENARIO_NATIONS必须同时与scenID和每个单元的nation连接起来(仅限于该场景),但我不知道如何做到这一点。
OMG小马的代码会导致每个单位被列出两次,每边一次,而不仅仅是其母国所在的那一边:
[scenID]  [side]   [nation]   [name]
BaBu001     1   America   CAPT
BaBu001     1   America   HMG
BaBu001     1   Germany   CAPT
BaBu001     1   Germany   GREN
BaBu001     2   America   CAPT
BaBu001     2   America   HMG
BaBu001     2   Germany   CAPT
BaBu001     2   Germany   GREN

正确的结果是
[scenID]  [side]   [nation]   [name]
BaBu001     1   America   CAPT
BaBu001     1   America   HMG
BaBu001     2   Germany   CAPT
BaBu001     2   Germany   GREN

为了达到这个目的,我们修改代码如下:
SELECT sn.side, snu.scenid, ubd.nation, ubd.unitname
FROM sn
JOIN snu
        ON snu.scenid=sn.scenid AND snu.scenid = 'scenID'
JOIN ubd
        ON ubd.nation=sn.nation AND ubd.unitid=snu.unitid //double join is the key change
ORDER BY sn.side, ubd.nation, ubd.unitname

最佳答案

如果只希望UNIT_BASIC_DATA行/记录与SCENARIO_NEEDUNITS表中的关系,请使用:

  SELECT snu.scenid,
         sn.side,
         ubd.nation,
         ubd.name
    FROM UNIT_BASIC_DATA ubd
    JOIN SCENARIO_NEEDUNITS snu ON snu.unitid = ubd.unitid
                               AND snu.scenid = ?
    JOIN SCENARIO_NATIONS sn ON sn.scenid = snu.scenid
ORDER BY snu.scenid, sn.side, ubd.nation, ubd.name

?替换为您希望查找的任何scenid
您不需要指定ASC-这是默认值。

07-24 09:31