0

I hope you can help. I want to do a keyword search on products including multiple tables. But not every product has any entries in each table...

Example

table 'product'
id     product_name     description
1      my product       this is my favorite product
2      another item     that is another product
3      blue car         for driving away

table 'keywords'
prod_id    keywords
2          car, product, blue

So, now I want to get all products, having 'car' in its 'product_name', 'description' or 'keywords'

Just using a simple mysql query will only have those products as result, which are in both tables:

SELECT A.id FROM product A, keywords B WHERE A.ID = B.product_id AND....

I tried LEFT JOIN - but that had all three products as result (maybe I did it wrong):

SELECT A.id FROM product A LEFT JOIN keywords B ON A.id = B.prod_id AND (A.product_name LIKE '%car%' OR A.description LIKE '%car%' OR B.keywords LIKE '%car%')

Can anyone help? Thanks & regards Jan

3 Answers 3

2

the best way is to use union

    select id from product where product_name LIKE '%car%' OR description LIKE '%car%'
    union 
    select prod_id as id from keywords where keywords LIKE '%car%' ;
Sign up to request clarification or add additional context in comments.

Comments

1

You put the AND in the LEFT JOIN instruction instead of WHERE. Try

SELECT `A.id` FROM product AS `A`
LEFT OUTER JOIN keywords AS `B` ON `A.id` = `B.prod_id`
WHERE (`A.product_name` LIKE '%car%' OR `A.description` LIKE '%car%' OR `B.keywords` LIKE '%car%')

Beware that LIKE '%car%' will also select That's my favorite cardigan.

RLIKE '[[:<:]]word[[:>:]]' may be better.


Resources:

Mysql RegExp for RLIKE: http://dev.mysql.com/doc/refman/5.0/fr/regexp.html

Comments

1

This can be done using an union:

(select id from product where product_name LIKE '%car%' OR description LIKE '%car%')
union 
(select prod_id from keywords where keywords LIKE '%car%' );

Comments

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.