连接 3 个表的查询

Query that joins 3 tables

CREATE TABLE User(uid INTEGER AUTO_INCREMENT,address VARCHAR(40),city 
VARCHAR(20),state VARCHAR(20),

到目前为止我尝试过的:

SELECT User.uid, Job.jobid, Protein.pid FROM User
JOIN Job ON (Job.uid = User.uid)
JOIN Protein ON (Job.pid = Protein.pid)

我不知道如何找到一份利用所有蛋白质的工作。

此查询将为您提供每项工作的 job_ids,该工作在蛋白质 table 中具有每个蛋白质之一,并且在蛋白质 table[= 中仅具有每个蛋白质之一15=]

select j.job_id
  from job j
    inner join job_proteins p
      on j.job_id = p.jid
  group by j.job_id
    having group_concat(p.pid order by p.pid asc) = 
      (select group_concat(pid order by pid asc) from protein);

演示:http://sqlfiddle.com/#!9/febf6/5

有必要添加一个额外的 table 来表示工作和蛋白质之间的关系,这在您的原始模式定义中缺失

如果一项工作永远不会使用超过一种相同的蛋白质是真的,那么下面的查询也足够了:

select j.job_id, count(j.job_id)
  from job j
    inner join job_proteins p
      on j.job_id = p.jid
  group by j.job_id
    having count(j.job_id) = (select count(pid) from protein);

已更新演示:http://sqlfiddle.com/#!9/febf6/9

注意更新后的演示 returns 具有相同蛋白质的示例作业列出了两次 - 因此要求作业不能使用多个相同的蛋白质。

如果一个作业可以多次使用相同的蛋白质,但没关系,并且您想将其包含在至少使用所有蛋白质一次的作业的结果中,则此查询就足够了:

select j.job_id, count(j.job_id)
  from job j
    inner join job_proteins p
      on j.job_id = p.jid
  group by j.job_id
    having count(distinct p.pid) = (select count(pid) from protein);