开发者

How do I filter out records with more than one matching key in MySQL?

I have two BMWs and two Mercedes and one Kia. They are in a MySQL table with car_id and brand.I want to know how what brands of car I only have one of. So what I expect returned is one record in this case with a brand of 'Kia' I don't want BMW or Mercedes to show up at all.

Edit

I've over simplified my problem. Sorry about that. So here's the real deal. I have a table with sid and hid. sid is unique but hid is not. I need to count the number of unique hid's. To do that I've done,

select count(distinct hid) from table

To count the full number of records there are I just looked at the number of rows returned from

select * from table

Now, given that hid should only appear either once or twice and given that I know how many times there are duplicate hid's, I should be able to add half of the number of duplicate hids on to the number of unique hids and end up with the full number of records. However, I'm off by 7. So to try to find the difference I tried to do...

select * from ( 
 select distinct hid from table group by hid
  union
 select hid from table group by hid) group by hid

thinking that this would return me any hids that are showing in the second query that are not in the first. It doesn't though and I'm pretty much stuck on where to go开发者_运维知识库 from here. Is there a way to take the two queries I have and get a diff on the hids?

I don't mean difference as in "subtract the total hids from the unique hids" I mean diff as in what hids are in the total that are not showing in the unique for some reason.


Use:

  SELECT t.hid
    FROM YOUR_TABLE t
GROUP BY t.hid
  HAVING COUNT(*) > 1

Previously:

  SELECT t.brand
    FROM YOUR_TABLE t
GROUP BY t.brand
  HAVING COUNT(*) = 1


It sounds as though you want a single query which will return both the total number of records and the number of hids that only occur once - if so, try:

select sum(count_hid) total_count, 
       sum(case count_hid when 1 then 1 else 0 end) singles_count
from
(select count(*) count_hid
 from your_table
 group by hid) sq
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜