在mysql中如何执行函数的子集?

ulmd4ohb  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(282)

添加:为学生和学生创建代码

CREATE TABLE `student` (
    `sid` VARCHAR(6) NOT NULL,
    `sname` VARCHAR(6) NULL DEFAULT NULL,
    `sex` VARCHAR(2) NULL DEFAULT NULL,
    `age` TINYINT(3) UNSIGNED NULL DEFAULT NULL,
    `dept` VARCHAR(50) NULL DEFAULT NULL,
    `class` VARCHAR(4) NULL DEFAULT NULL,
    PRIMARY KEY (`sid`)
);

CREATE TABLE `takes` (
    `sid` VARCHAR(6) NOT NULL,
    `cid` VARCHAR(3) NOT NULL,
    `score` TINYINT(3) UNSIGNED NULL DEFAULT NULL,
    PRIMARY KEY (`sid`, `cid`)
)

我将显示所有参加课程的学生的id和姓名,这些课程是由id为“31401”的学生参加的。我有以下代码:

SELECT sid, sname
FROM student S
WHERE NOT EXISTS((SELECT cid
                 FROM takes
                 WHERE sid = '31401')
                 EXCEPT
                 (SELECT cid
                 FROM takes T
                 WHERE S.sid = T.sid));

然而,mysql中没有except操作。所以我想知道我是否可以这样重写:

SELECT sid, sname
FROM student S
WHERE ((SELECT cid
        FROM takes
        WHERE sid = '31401')
        IS_THE_SUBSET_OF
       (SELECT cid
        FROM takes T
        WHERE S.sid = T.sid));

如何实现函数的子集?

6l7fqoea

6l7fqoea1#

没有基于集合的运算符可以满足您的需要。你可以用 join , group by 还有其他一些逻辑:

select t.sid
from takes t join
     takes ts
     on t.cid = ts.cid and ts.sid = 31401  -- don't use single quotes for a numeric constant
group by t.sid
having count(*) = (select count(*) from takes ts2 where ts2.sid = 31401);

这个公式假设 takes 没有重复项 sid / cid 对。

相关问题