Roger writes "This is a bit messy to describe! Rather simplified, I have two tables, one with addresses (A) and one with names (N), each name joined to an address by an ID field. I want to search for a string which may be in either the address or the name, and return a minimal but complete set of rows. By this I mean all the names that match, plus a single row for each address which matches without a name matching. Such asResults for "Bob"ABC Company (Bob Johnson)ABC Company (Bob Zurich)Bobsleigh Group (Anne Smith)SQL Team (Robert Jones)My best effort is this ... the NID term is so that I can format the results depending whether the match was in a name or address.SELECT A.Address1 as Address, (SELECT TOP 1 N.Name FROM N WHERE N.Card_id = A.Card_ID) as Name1, -1 as NID FROM AWHERE A.Address1 + A.Address2 LIKE '%bob%' AND NOT EXISTS(SELECT N.Name FROM N WHERE A.Card_id = N.Card_ID AND N.Name LIKE '%bob%') UNIONSELECT A.Address1 as Address, N.Name as Name1, N.ID as NIDFROM A JOIN N on (N.Card_id = A.Card_ID) WHERE N.Name LIKE '%bob%'ORDER BY Address, Name
This gets really messy when expanded so that (in real life) the target might be in several fields or even have one part in the name and one part in the address (find "sqlteam tibet"). Can you suggest anything elegant?Best wishes, Roger."