Reputation: 796
I have two tables and a search form to just search for a keyword. I am trying to search for that keyword on two table for multiple columns and if the query matches get the id column for further use. I have tried this (suppose "coupon" is the term user is searching for)
SELECT `ID` FROM `Profiles` AS `p` WHERE `p`.`Status` = 'Active' AND `p`.`Address`
LIKE '%coupon%' OR `p`.`BusinessName` LIKE '%coupon%' OR `p`.`BusinessSubCategory`
LIKE '%coupon%' OR `p`.`DescriptionMe` LIKE '%coupon%' OR `p`.`Tags` LIKE '%coupon%'
UNION SELECT `id` FROM `products` AS `d` WHERE `d`.`status` = 'approved' AND
`d`.`title` LIKE '%coupon%' OR `d`.`desc` LIKE '%coupon%' OR `d`.`tags` LIKE '%coupon%'
Here i want the id of profile and id of products that matches the keyword. I tried this and this is returning very strange results and looks like only profile ID. So, its a wrong query. What should be the query for this kind of search? INNER JOIN? Please give me some sample queries for this, i will be very grateful for any help.
Upvotes: 1
Views: 168
Reputation: 13465
Try this::
SELECT `ID`,'profile_ID' FROM
`Profiles` AS `p`
WHERE `p`.`Status` = 'Active' AND `p`.`Address`
LIKE '%coupon%' OR `p`.`BusinessName` LIKE '%coupon%' OR `p`.`BusinessSubCategory`
LIKE '%coupon%' OR `p`.`DescriptionMe` LIKE '%coupon%' OR `p`.`Tags` LIKE '%coupon%'
UNION ALL
SELECT `id`, 'productID' FROM `products` AS `d` WHERE `d`.`status` = 'approved' AND
`d`.`title` LIKE '%coupon%' OR `d`.`desc` LIKE '%coupon%' OR `d`.`tags` LIKE '%coupon%'
Upvotes: 1
Reputation: 1475
First off, I wouldn't use AS p
when you're not doing an INNER JOIN
etc... seems like overdoing it plus I guess you need parentheses after AND
- surrounding the OR
s as well if you explicity want the to find results where status is "Active".
How about:
SELECT ID FROM Profiles WHERE Status = 'Active' AND (Address LIKE '%coupon%' OR BusinessName LIKE '%coupon%' OR BusinessSubCategory LIKE '%coupon%' OR DescriptionMe LIKE '%coupon%' OR Tags LIKE '%coupon%')
UNION SELECT id FROM products WHERE status = 'approved' AND (title LIKE '%coupon%' OR desc LIKE '%coupon%' OR tags LIKE '%coupon%')
Upvotes: 2