左连接但不能保留右表中左表中的每个类别

时间:2015-11-12 16:13:25

标签: mysql

我有两张桌子:

Table one:
Subjects:
A
B
C
D

Table two:
ID Subjects score
001 A 3
001 B 2
001 D 5
002 A 4
002 B 3
002 C 6
002 D 7

003 A 2
003 C 1
003 D 0

我想结合这两个表并得到像这样的结果

001 A 3
001 B 2
001 C 
001 D 5
002 A 4
002 B 3
002 C 6
002 D 7
003 A 2
003 B 
003 C 1
003 D 0

对于身份证号码001,我需要证明他对主题C的记录是空白的,如001 C。但在我的结果中,它总是像下面一样缺失

 . But in my results, it's always missing like below

001 A 3
001 B 2
001 D 5
002 A 4
002 B 3
002 C 6
002 D 7
003 A 2
003 C 1
003 D 0

我的查询就像

Select two.*
  from one 
  left 
  join two
    on one.subjects = two.subjects

2 个答案:

答案 0 :(得分:1)

http://sqlfiddle.com/#!9/b4bbc9/5

SELECT t.id, t.subjects, res.score
FROM t2 res
RIGHT JOIN (
SELECT DISTINCT t2.id, t1.subjects
FROM t2
LEFT JOIN t1
ON 1
) t
ON res.id = t.id
AND res.subjects = t.subjects
ORDER BY t.id , t.subjects;

答案 1 :(得分:0)

我已经扩展了你的例子,使其更具代表性......

DROP TABLE IF EXISTS one;

CREATE TABLE one
(my_subject CHAR(1) NOT NULL PRIMARY KEY);

INSERT INTO one VALUES
('A'),
('B'),
('C'),
('D'),
('E');


DROP TABLE IF EXISTS two;

CREATE TABLE two
(id INT NOT NULL
,my_subject CHAR(1) NOT NULL
,score INT NOT NULL
,PRIMARY KEY(id,my_subject)
);

INSERT INTO two VALUES
(1,'A',3),
(1,'B',2),
(1,'D',5),
(2,'A',4),
(2,'B',3),
(2,'C',6),
(2,'D',7),
(3,'A',2),
(3,'C',1),
(3,'D',0);

SELECT DISTINCT a.id
              , one.my_subject
              , b.score  
           FROM one 
           JOIN two a 
           LEFT 
           JOIN two b  
             ON b.id = a.id 
            AND b.my_subject = one.my_subject

+----+------------+-------+
| id | my_subject | score |
+----+------------+-------+
|  1 | A          |     3 |
|  1 | B          |     2 |
|  1 | C          |  NULL |
|  1 | D          |     5 |
|  1 | E          |  NULL |
|  2 | A          |     4 |
|  2 | B          |     3 |
|  2 | C          |     6 |
|  2 | D          |     7 |
|  2 | E          |  NULL |
|  3 | A          |     2 |
|  3 | B          |  NULL |
|  3 | C          |     1 |
|  3 | D          |     0 |
|  3 | E          |  NULL |
+----+------------+-------+