2011-03-09 42 views
0

例如,假设我有以下的加入我可以在MySQL的JOIN子句中添加条件吗?

join on p.match_id = o.match_id 

我可以指定代替,如果p.match_id是即使在当时

join on p.match_id = o.match_id - 1 

但如果是奇数则

join on p.match_id = o.match_id + 1 

我具有顺序match_id,以便连续值代表单个匹配。因此,要制定出一个对手对于一个给定match_id我需要上述

+4

如果你的数据需要,我会非常关注 –

+0

这样做有什么逻辑吗?你可能会考虑替代 –

+1

它的确如此,因为我有顺序match_id,这样连续的值代表单个匹配。因此,要找出给定match_id的对手,我需要上面的 – deltanovember

回答

4

编辑,以便它不使用CASE。子查询返回一个包含一个字段的表:matchid(match_id为偶数时为match_id + 1,match_id为奇数时为match_id-1)。

SELECT matchid 
    FROM (SELECT match_id + 1 - 2*(match_id % 2) 
       AS matchid 
      FROM p 
     ) AS p2 
    JOIN o 
    ON p2.matchid = o.match_id 
; 

既然你提到你正在使用一个表和2个sequentials IDS的一对对手,你也可以使用下面的子查询或视图:

SELECT match_id 
    , ((match_id + 1) DIV 2) AS pair 
    FROM p 
; 

它会给你然后你可以收集自己的表格:

| match_id | pair | 
|  1 | 1 | 
|  2 | 1 | 
|  3 | 2 | 
|  4 | 2 | 
|  5 | 3 | 
|  6 | 3 | 
+0

聪明而优雅的谢谢! – deltanovember

+1

@deltanovember:'pair'这里基本上是游戏(匹配)ID,通常应该是一个外键。但是,这是你的粥,使用自己的勺子(或选择最适合你的一个)。 :) –

1

我认为,如果你想只能加入就连p.match_id的价值,您需要做的有一点不同:

join on p.match_id = o.match_id and p.match_id = p.match_id div 2 * 2 

同样,如果他们应该是奇数:

join on p.match_id = o.match_id and p.match_id = p.match_id div 2 * 2 + 1 

但是和其他人一样,我很好奇你为什么需要这个。一个id列仅仅是一个id列。通常你不应该对id列的值的特定特征感兴趣。

4

如果你想加入一个表与另一个在第2台的ID,甚至只,试试这个:

JOIN ON p.match_id = o.match_id AND o.match_id % 2 = 0 

或者第二表的编号为奇数:

JOIN ON p.match_id = o.match_id AND o.match_id % 2 = 1 
+0

嘿,这比我的解决方案好多了!我为什么没有想到这个? –

相关问题