t1 表含有数据:
小张,c语言
小张, 数据结构
小刘,go语言
t2表含有数据:
小张,c语言
小张, 数据结构
小张,高数
小刘,go语言
小刘,perl
小王,android
现在要找出t2表中name相同,course列比t1表中多出的记录:
小张,高数
小刘,perl
4 个解决方案
#1
select t2.`name`,t2.`course` from t1 inner join t2 on t1.`name`=t2.`name` and not exists(select 1 from t1 where t2.`name`=t1.`name` and t2.`course`=t1.`course`);
#2
USE test;
DROP TABLE
IF EXISTS `t1`;
CREATE TABLE t1 (
`name` VARCHAR (10) NOT NULL,
`course` VARCHAR (10) NOT NULL
) ENGINE = MyISAM DEFAULT CHARSET = utf8;
DROP TABLE
IF EXISTS `t2`;
CREATE TABLE t2 (
`name` VARCHAR (10) NOT NULL,
`course` VARCHAR (10) NOT NULL
) ENGINE = MyISAM DEFAULT CHARSET = utf8;
INSERT t1
VALUES
('小张', 'c语言'),
('小张', '数据结构'),
('小刘', 'go语言');
INSERT t2
VALUES
('小张', 'c语言'),
('小张', '数据结构'),
('小张', '高数'),
('小刘', 'go语言'),
('小刘', 'perl'),
('小王', 'android');
SELECT DISTINCT
t2.`name`,
t2.`course`
FROM
t1
INNER JOIN t2 ON t1.`name` = t2.`name`
AND NOT EXISTS (
SELECT
1
FROM
t1
WHERE
t2.`name` = t1.`name`
AND t2.`course` = t1.`course`
);
DROP TABLE t1;
DROP TABLE t2;
#3
SELECT * FROM t2
WHERE t2.name IN (SELECT NAME FROM t1 GROUP BY NAME)
AND
t2.course NOT IN (SELECT course FROM t1 )
#4
SELECT * FROM t2
WHERE t2.name IN (SELECT NAME FROM t1 GROUP BY NAME)
AND
t2.course NOT IN (SELECT course FROM t1 )
WHERE t2.name IN (SELECT NAME FROM t1 GROUP BY NAME)
AND
t2.course NOT IN (SELECT course FROM t1 )
#1
select t2.`name`,t2.`course` from t1 inner join t2 on t1.`name`=t2.`name` and not exists(select 1 from t1 where t2.`name`=t1.`name` and t2.`course`=t1.`course`);
#2
USE test;
DROP TABLE
IF EXISTS `t1`;
CREATE TABLE t1 (
`name` VARCHAR (10) NOT NULL,
`course` VARCHAR (10) NOT NULL
) ENGINE = MyISAM DEFAULT CHARSET = utf8;
DROP TABLE
IF EXISTS `t2`;
CREATE TABLE t2 (
`name` VARCHAR (10) NOT NULL,
`course` VARCHAR (10) NOT NULL
) ENGINE = MyISAM DEFAULT CHARSET = utf8;
INSERT t1
VALUES
('小张', 'c语言'),
('小张', '数据结构'),
('小刘', 'go语言');
INSERT t2
VALUES
('小张', 'c语言'),
('小张', '数据结构'),
('小张', '高数'),
('小刘', 'go语言'),
('小刘', 'perl'),
('小王', 'android');
SELECT DISTINCT
t2.`name`,
t2.`course`
FROM
t1
INNER JOIN t2 ON t1.`name` = t2.`name`
AND NOT EXISTS (
SELECT
1
FROM
t1
WHERE
t2.`name` = t1.`name`
AND t2.`course` = t1.`course`
);
DROP TABLE t1;
DROP TABLE t2;
#3
SELECT * FROM t2
WHERE t2.name IN (SELECT NAME FROM t1 GROUP BY NAME)
AND
t2.course NOT IN (SELECT course FROM t1 )
#4
SELECT * FROM t2
WHERE t2.name IN (SELECT NAME FROM t1 GROUP BY NAME)
AND
t2.course NOT IN (SELECT course FROM t1 )
WHERE t2.name IN (SELECT NAME FROM t1 GROUP BY NAME)
AND
t2.course NOT IN (SELECT course FROM t1 )