MySQL选择数据对

时间:2013-01-07 21:18:23

标签: mysql sql select

我有两张桌子:

CREATE TABLE `digits` (
  `digit` tinyint(3) unsigned NOT NULL,
  `group` tinyint(3) unsigned NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

INSERT INTO `digits` (`digit`, `group`) VALUES
(1, 1),
(2, 1),
(3, 1),
(4, 2),
(5, 2);

CREATE TABLE `scores` (
  `digit1` tinyint(3) unsigned NOT NULL,
  `digit2` tinyint(3) unsigned NOT NULL,
  `score` tinyint(3) unsigned NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

INSERT INTO `scores` (`digit1`, `digit2`, `score`) VALUES
(1, 2, 5),
(1, 4, 9),
(2, 3, 3);

我想做的是选择所有数字组合(不重复)和分数,如果没有分数则选择null

示例答案(WHERE group <=1):

digit1 | digit2 | score
-----------------------
1      | 2      | 5
1      | 3      | null
2      | 3      | 3

示例答案(WHERE group <=2):

digit1 | digit2 | score
-----------------------
1      | 2      | 5
1      | 3      | null
1      | 4      | 9
1      | 5      | null
2      | 3      | 3
2      | 4      | null
2      | 5      | null
3      | 4      | null
3      | 5      | null
4      | 5      | null

1 个答案:

答案 0 :(得分:2)

试试这个:

select d1.digit, d2.digit, s.score
from digits d1 join
     digits d2
     on d1.group <= <groupnumber> and
        d2.group <= <groupnumber> and
        d1.digit < d2.digit left outer join
     score s
     on s.digit1 = d1.digit and
        s.digit2 = d2.digit