mysql: joining 2 tables and compute multiple counts & sort results -


i beginner mysql , have problem can't solve myself. hope guys know how me.

i have 2 tables. first table x maps users license plates:

user_id | license_id    1    |        1    |     b    1    |     c    2    |     d    2    |     e    ... 

the second table y maps license plates insurances:

license_id | insurance_id | year          |      i1     | 2001          |      i2     | 2002          |      i3     | 2003          |      i2     | 2004    b       |      i2     | 2002    b       |      i2     | 2003    d       |      i2     | 2003    d       |      i2     | 2004    d       |      i2     | 2005    e       |      i3     | 2004    ... 

and want answer following questions in efficient way, because tables rather large:

given set of insurances (i1, i2), show me users, registered @ least 1 of them. sort number of matching insurances, count multiple registrations of same user same insurance (because of different license ids) once. further, each user, show me license id, shows insurance matches, given user , above set of insurances, not count distinctly here.

let's have insurance set (i1, i2), expect result follows:

user_id | num_matches | license_id | num_matches_license_id    1    |      2      |          |      3    2    |      1      |      d     |      3 

as of right now, achieved count user matches:

select x.user_id user_id, y.license_id license_id, y.insurance_id insurance_id, count(distinct insurance_id) num_matches y join x on x.license_id=y.license_id y.license_id in (i1,i2) group user_id order num_matches desc 

i don't head around how include license matches well? since grouping results user_id, lose license information...


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -