0

I have two tables:

Clients: id, name Texts: id, text

Field text in Texts table can contain names of clients. I would like to find for each text, clients whose names are contained in text field. For example:

CLIENTS
id | name
1  | John Smith
2  | Mark Jackson
3  | Ann Boo

TEXTS
id | text
1  | John Smith and Ann Boo are my best friends.
2  | I really don't like Mark Jackson and John Smith.

The result should be:

RESULT
Text.id | Client.id | Client.name
1       | 1         | John Smith
1       | 3         | Ann Boo
2       | 1         | John Smith
2       | 2         | Mark Jackson

I hope you will help me :) I want to know what parameters should find() function have or just mysql query

2
  • If going this route you'll end up having to search for each single word in the text field. It'd probably make more sense to redesign how you store the relations to clients from the texts table. Think of how you can tag users in a facebook status, if you've used that. The user has to specify that it's a link to another user. Commented Jun 29, 2011 at 10:21
  • I've tried to do this in loop. Foreach text SELECT * FROM clients WHERE %name% LIKE $text['text'] but can't do this with cakephp. :/ Commented Jun 29, 2011 at 10:29

1 Answer 1

1
DECLARE @clients TABLE (ID int IDENTITY(1,1), name VARCHAR(20))
INSERT @clients (name)
SELECT 'John Smith' UNION ALL SELECT 'Mark Jackson' UNION ALL SELECT 'Ann Boo'

DECLARE @texts TABLE (ID int IDENTITY(1,1), [text] VARCHAR(200))

INSERT @texts ([text]) VALUES ('John Smith and Ann Boo are my best friends.')
INSERT @texts ([text]) VALUES ('I really don''t like Mark Jackson and John Smith.')

SELECT T.id  [Text.id], C.id [Client.id], C.name [Client.name] 
FROM @CLIENTS C 
JOIN @TEXTS T 
ON T.[text] LIKE '%' + C.NAME + '%'

RESULT

Text.id     Client.id   Client.name
----------- ----------- --------------------
1           1           John Smith
1           3           Ann Boo
2           1           John Smith
2           2           Mark Jackson
Sign up to request clarification or add additional context in comments.

2 Comments

'%' + C.NAME + '%' is it correct in MySQL cause it doesn't work for me. :(
solution is: CONCAT('%', C.NAME, '%')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.