计算具有多个条件的两个表
Counting two tables with several conditions
我有两个表,
fenotipos
id DTHHRDX sex
GTEX-1117F 0 2
GTEX-ZE9C 2 1
K-562 1 2
atributos
SAMPID SMTS
K-562-SM-26GMQ Blood vessel
K-562-SM-2AXTU Blood_dry
GTEX-1117F-0003-SM-58Q7G Brain
GTEX-ZE9C-0006-SM-4WKG2 Brain
GTEX-ZE9C-0008-SM-4E3K6 Urine
GTEX-ZE9C-0011-R11a-SM-4WKGG Urine
我需要知道有多少女性 (sex
=2) DTHHRDX
= 1 并且 SMTS
.
上有血
例如,这种情况下的答案是 2
你可以这样做:
select count(*) as cnt
from fenotipos f
where
sex = 2
and exists (
select 1
from atributos a
where a.sampid like concat(f.id, '%') and a.smts like 'Blood%'
)
这可以正确处理 atributos
中潜在的多个匹配项
或者,您可以加入:
select count(distinct f.id) as cnt
from fenotipos f
inner join atributos a on a.sampid like concat(f.id, '%')
where f.sex = 2 and a.smts like 'Blood%'
如果没有重复项,那么在第二个查询中 count(*)
比 count(distinct f.id)
更有效。
我有两个表,
fenotipos
id DTHHRDX sex
GTEX-1117F 0 2
GTEX-ZE9C 2 1
K-562 1 2
atributos
SAMPID SMTS
K-562-SM-26GMQ Blood vessel
K-562-SM-2AXTU Blood_dry
GTEX-1117F-0003-SM-58Q7G Brain
GTEX-ZE9C-0006-SM-4WKG2 Brain
GTEX-ZE9C-0008-SM-4E3K6 Urine
GTEX-ZE9C-0011-R11a-SM-4WKGG Urine
我需要知道有多少女性 (sex
=2) DTHHRDX
= 1 并且 SMTS
.
例如,这种情况下的答案是 2
你可以这样做:
select count(*) as cnt
from fenotipos f
where
sex = 2
and exists (
select 1
from atributos a
where a.sampid like concat(f.id, '%') and a.smts like 'Blood%'
)
这可以正确处理 atributos
或者,您可以加入:
select count(distinct f.id) as cnt
from fenotipos f
inner join atributos a on a.sampid like concat(f.id, '%')
where f.sex = 2 and a.smts like 'Blood%'
如果没有重复项,那么在第二个查询中 count(*)
比 count(distinct f.id)
更有效。