我遇到了这个使用三个不同表的查询的问题。我也相信我会使用关键词NOT EXISTS而不是WITHIN但我对此并不完全正面。我将发布查询定义,我正在使用的表,以及到目前为止我尝试过的内容。感谢您的帮助!
查询:
Find the users that create jobs that utilize all proteins.
表格:
CREATE TABLE Protein(pid INTEGER,name varchar(50),PRIMARY KEY(pid));
CREATE TABLE Job(uid INTEGER,job_id INTEGER AUTO_INCREMENT,input
varchar(500),status varchar(100),start_time time,finish_time time,FOREIGN
KEY(uid) REFERENCES User(uid) ON DELETE CASCADE,PRIMARY KEY(job_id));
CREATE TABLE User(uid INTEGER AUTO_INCREMENT,address VARCHAR(40),city
VARCHAR(20),state VARCHAR(20),zipcode VARCHAR(10), username
VARCHAR(10),email VARCHAR(30),primary key (uid));
CREATE TABLE job_protein(job_id INTEGER, pid INTEGER, PRIMARY KEY(job_id, pid));
到目前为止我尝试了什么......
SELECT u.uid, j.jobid, count(j.jobid)
FROM job j
INNER JOIN job_proteins p
ON j.jobid = p.jobid
INNER JOIN user u
ON p.uid = u.uid
GROUP BY j.jobid
HAVING count(j.jobid) = (SELECT count(pid) FROM Protein);
我有什么工作可以利用每种蛋白质?
答案 0 :(得分:1)
在组中缺少成员:
SELECT u.uid, j.jobid, count(j.jobid)
FROM job j
INNER JOIN job_proteins p
ON j.jobid = p.jobid
INNER JOIN user u
ON p.uid = j.uid -- and you had wrong alias here
GROUP BY u.uid, j.jobid -- right here
HAVING count(j.jobid) = (SELECT count(pid) FROM Protein);
答案 1 :(得分:0)
您可以简化查询,因为您似乎不需要user
表。
其次,您的问题陈述含糊不清。如果目标是找到一个作业的用户应该拥有所有蛋白质,那么以下内容将获得用户/工作对:
SELECT j.uid, jp.jobid, count(*)
FROM job j JOIN
job_proteins jp
ON j.jobid = jp.jobid
GROUP BY j.uid, jp.jobid
HAVING count(distinct jp.pid) = (SELECT count(*) FROM Protein);
略微修改只会让用户:
SELECT DISTINCT j.uid
FROM job j JOIN
job_proteins jp
ON j.jobid = jp.jobid
GROUP BY j.uid, jp.jobid
HAVING count(distinct jp.pid) = (SELECT count(*) FROM Protein);
注意:这是SELECT DISTINCT
与GROUP BY
一起使用的极少数情况之一。
如果目标是找到在其工作中使用 all 蛋白质的用户:
SELECT j.uid
FROM job j JOIN
job_proteins jp
ON j.jobid = jp.jobid
GROUP BY j.uid
HAVING count(distinct jp.pid) = (SELECT count(*) FROM Protein);
与第一个查询的区别在于GROUP BY
子句已更改。