Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 基于条件行从另一个表中查找结果_Mysql - Fatal编程技术网

Mysql 基于条件行从另一个表中查找结果

Mysql 基于条件行从另一个表中查找结果,mysql,Mysql,我有两张表,一张是养宠物的家庭名单,另一张是潜在收养者名单 有些家庭一次(全部)送出他们所有的宠物,但有些家庭将它们分开(一个)送出。这在“多少”行中表示 考虑到动物,领养者有偏好,一些人只领养一只特定的动物,另一些人会领养不止一只 我想实现的是编写一个查询,将家庭与潜在的采纳者联系起来 因此,如果有一个家庭会送出一只猫和一只鸟(不是分开的),例如威廉姆斯家庭(ID 3,全部),他们将与用户4连接,用户4希望收养一只猫和一只鸟(除了一只狗,但这没关系,不是所有3个都必须匹配,只是一个子集) 或者

我有两张表,一张是养宠物的家庭名单,另一张是潜在收养者名单

有些家庭一次(全部)送出他们所有的宠物,但有些家庭将它们分开(一个)送出。这在“多少”行中表示

考虑到动物,领养者有偏好,一些人只领养一只特定的动物,另一些人会领养不止一只

我想实现的是编写一个查询,将家庭与潜在的采纳者联系起来

因此,如果有一个家庭会送出一只猫和一只鸟(不是分开的),例如威廉姆斯家庭(ID 3,全部),他们将与用户4连接,用户4希望收养一只猫和一只鸟(除了一只狗,但这没关系,不是所有3个都必须匹配,只是一个子集)

或者,如果有一个家庭会单独送出他们的宠物,例如史密斯家庭(ID 1,1),他们会与所有想收养鸟或猫的收养者联系,如用户1、用户2等

有没有一种方法可以在一个查询中实现这一点

Families

id  animal  family      how_many

1   bird    Smith       one
1   cat     Smith       one
2   bird    Johnson     one
2   dog     Johnson     one
3   cat     Williams    all      
3   bird    Williams    all
4   bird    Brown       one
5   cat     Jones       all
6   bird    Miller      all
7   bird    Davis       one
7   cat     Garcia      one
7   bird    Garcia      one
7   dog     Garcia      one


Adopters

id  animal  adopter
1   cat     User 1
1   bird    User 1
2   bird    User 2
2   dog     User 2
3   bird    User 3
3   dog     User 4
4   cat     User 4
4   dog     User 4
4   bird    User 4
5   bird    User 5
6   bird    User 6

嗯。我认为最合理的方法是合并两个查询,一个用于“一”查询,另一个用于“所有”查询:


非常感谢。这正是我需要的。
select f.*, a.id
from families f join
     adopters a
     on f.animal = a.animal 
where f.how_many = 'one'
union all
select f.id, group_concat(f.animal), f.family, f.how_many, a.id
from families f left join
     adopters a
     on f.animal = a.animal 
where f.how_many = 'all'
group by f.id, f.family, f.how_many, a.id
having count(*) = count(a.animal);