如何根据多个行值从 MySQL table 等数据透视表中获取不同的 id?
How to get distinct ids from a pivot like MySQL table according to multiple row values?
我有一个 MySQL table 像下面这个名字 attribute_master,
现在我想获得所有 ref_id 具有 f_name = "Sam"
和 l_name = "Border"
.
我如何使用 MySQL 查询来做到这一点?
您可以使用聚合:
select ref_id
from mytable
where attr_name in ('f_name', 'l_name')
group by ref_id
having
max(attr_name = 'f_name' and attr_value = 'Sam') = 1
and max(attr_name = 'l_name' and attr_value = 'Border') = 1
这是另一种表达方式(假设没有重复(ref_id, attr_name)
):
select ref_id
from mytable
where (attr_name, attr_value) in (('f_name', 'Sam'), ('l_name', 'Boder'))
group by ref_id
having count(*) = 2
我有一个 MySQL table 像下面这个名字 attribute_master,
现在我想获得所有 ref_id 具有 f_name = "Sam"
和 l_name = "Border"
.
我如何使用 MySQL 查询来做到这一点?
您可以使用聚合:
select ref_id
from mytable
where attr_name in ('f_name', 'l_name')
group by ref_id
having
max(attr_name = 'f_name' and attr_value = 'Sam') = 1
and max(attr_name = 'l_name' and attr_value = 'Border') = 1
这是另一种表达方式(假设没有重复(ref_id, attr_name)
):
select ref_id
from mytable
where (attr_name, attr_value) in (('f_name', 'Sam'), ('l_name', 'Boder'))
group by ref_id
having count(*) = 2