Select multiple rows with the same value(s)

前端 未结 5 1094
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 10:17

I have a table, sort of like this:

ID  |  Chromosome | Locus | Symbol | Dominance |
===============================================
1   |      10     |   2           


        
相关标签:
5条回答
  • 2020-12-13 10:19

    One way of doing this is via an exists clause:

    select * from genes g
    where exists
    (select null from genes g1
     where g.locus = g1.locus and g.chromosome = g1.chromosome and g.id <> g1.id)
    

    Alternatively, in MySQL you can get a summary of all matching ids with a single table access, using group_concat:

    select group_concat(id) matching_ids, chromosome, locus 
    from genes
    group by chromosome, locus
    having count(*) > 1
    
    0 讨论(0)
  • 2020-12-13 10:21

    This may work for you:

    select t1.*
    from table t1
    join (select t2.Chromosome, t2.Locus
        from table2
        group by t2.Chromosome, t2.Locus
        having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus
    
    0 讨论(0)
  • 2020-12-13 10:22

    The problem is GROUP BY - if you group results by Locus, you only get one result per locus.

    Try:

    SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10';
    

    If you prefer using HAVING syntax, then GROUP BY id or something that is not repeating in the result set.

    0 讨论(0)
  • 2020-12-13 10:41

    You need to understand that when you include GROUP BY in your query you are telling SQL to combine rows. you will get one row per unique Locus value. The Having then filters those groups. Usually you specify an aggergate function in the select list like:

    --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'
    
    0 讨论(0)
  • 2020-12-13 10:44

    Assuming that you want all rows for which there is another row with the exact same Chromosome and Locus:

    You can achieve this by joining the table to itself, but only returning the columns from one "side" of the join.

    The trick is to set the join condition to "the same locus and chromosome":

    select left.*
    from Genes left
    inner join Genes right
    on left.Locus = right.Locus and 
      left.Chromosome = right.Chromosome and left.ID != right.ID
    

    You can also easily extend this by adding a filter in a where-clause.

    0 讨论(0)
提交回复
热议问题