我有一张桌子,有点像这样:
ID | Chromosome | Locus | Symbol | Dominance |
===============================================
1 | 10 | 2 | A | Full |
2 | 10 | 2 | a | Rec. |
3 | 10 | 3 | B | Full |
4 | 10 | 3 | b | Rec. |
Run Code Online (Sandbox Code Playgroud)
我想选择具有相同基因座和染色体的所有行.例如,第3行和第4行.一次可能超过2个,它们可能不是有序的.
我试过这个:
SELECT *
FROM Genes
GROUP BY Locus
HAVING Locus='3' AND Chromosome='10'
Run Code Online (Sandbox Code Playgroud)
但它总是返回第3行,从不返回第4行,即使重复也是如此.我想我错过了一些明显而简单的东西,但我很茫然.
有人可以帮忙吗?
KM.*_*KM. 39
您需要了解当您GROUP BY在查询中包含时,您要告诉SQL组合行.每个唯一Locus值将获得一行.在Having随后过滤这些组.通常在选择列表中指定aggergate函数,如:
--show how many of each Locus there is
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus
--only show the groups that have more than one row in them
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus HAVING COUNT(*)>1
--to just display all the rows for your condition, don't use GROUP BY or HAVING
SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10'
Run Code Online (Sandbox Code Playgroud)
Mat*_*ick 10
假设您希望所有行与另一行完全相同,Chromosome并且Locus:
您可以通过将表连接到自身来实现此目的,但只能从连接的一个"侧"返回列.
诀窍是将连接条件设置为"相同的基因座和染色体":
select left.*
from Genes left
inner join Genes right
on left.Locus = right.Locus and
left.Chromosome = right.Chromosome and left.ID != right.ID
Run Code Online (Sandbox Code Playgroud)
您还可以通过在where-clause中添加过滤器来轻松扩展它.