mysql - select where member only belongs to one customer -


i having trouble figuring out query. have 3 tables

messages --------------- message_id phone_num body received_time  subscribers --------------- phone_num keyword_id  keywords --------------- keyword_id client_id 

subscribers can belong many keywords of different clients. want find recent messages of subscribers belong 1 particular client no others, 1 client total.

for example looking recent messages subscribers belong client 1, data:

message_id      phone_num   body         received_time 1               111         hi           123456 2               222         test         123489 3               333         msg          213445  phone_num   keyword_id 111         1 111         2 222         3 333         4 333         5  keyword_id      client_id 1               1 2               1 3               1 4               1 5               4 

i want get:

message_id   phone_num   body   received_time 2            222         test   123489 1            111         hi     123456 

since numbers 111 , 222 belong 1 client

make sense? can't figure out. thanks

i builded complex query:

select   m.message_id, m.phone_num, m.body, m.received_time    messages m  m.phone_num in (   select      phone_num         subscribers s,     keywords k        s.keyword_id = k.keyword_id ,     k.client_id = 1 ,     s.phone_num in (       select          s.phone_num                subscribers s, keywords k               s.keyword_id = k.keyword_id       group s.phone_num       having count(distinct k.client_id) = 1     ) ) 

the inner subquery fetches "unique" numbers, e.g. numbers belong only one client.

the middle-inner subquery fetches among these numbers those, belong desired client (note k.client_id = 1).

and outer query fetches messages, numbers found in phone list.

note performance: middle subquery okay if put index on client_id field. inner query bit problematic, since examines rows of keywords table. size/number_of_rows in tables?

hope you.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -