简体   繁体   中英

PHP/MySQL Search Engine Query for keywords in a related table

I am trying to create a search function for my website. I have a main table called 'releases' which contains all of the main pages to search through. I have a second table called releases_index which contains keywords for each page.

Example:

releases:

# releases_id, releases_title
'10001', 'Scarlet Witch'
'10002', 'Vision'

releases_index:

# index_id, index_releaseId, index_value
'1', '10001', 'Scarlet Witch'
'2', '10001', 'Television'
'3', '10001', 'WandaVision'
'4', '10002', 'Vision'
'5', '10002', 'Television'
'6', '10002', 'WandaVision'

I am struggling to create an SQL query that can return the correct results. For example, if on the website I searched for 'scarlet witch' I want it to return index_releaseId 10001. I also want it to return this if I search for 'scarlet witch wandavision'.

Originally I was trying to do this with something like the below, but the problem was that it was looking for rows that contained the entire search query rather than release ID's which matched all of the query terms.

WHERE index_value LIKE '%scarlet%' AND index_value LIKE '%witch%' AND index_value LIKE '%wandavision%'

Can anyone advise what the best way do to do this is? I am doing this in PHP with PDO/MySQL

Here is the version that that I would use to achieve this:

     SELECT index_releaseId, GROUP_CONCAT(index_value) as idx_values
       FROM releases_index
   GROUP BY index_releaseId
     HAVING idx_values LIKE '%scarlet%'
        AND idx_values LIKE '%witch%'
        AND idx_values LIKE '%wandavision%'

Side note: GROUP_CONCAT is a vendor specific function and only available in MySQL/MariaDB

As you search for each search words that have to be valid

CREATE TABLE table1 ( `index_id` VARCHAR(3), `index_releaseId` VARCHAR(7), `index_value` VARCHAR(15) ); INSERT INTO table1 (`index_id`, `index_releaseId`, `index_value`) VALUES ('1', '10001', 'Scarlet Witch'), ('2', '10001', 'Television'), ('3', '10001', 'WandaVision'), ('4', '10002', 'Vision'), ('5', '10002', 'Television'), ('6', '10002', 'WandaVision');
 SELECT DISTINCT `index_releaseId` FROM table1 t1 WHERE EXISTS(SELECT 1 FROM table1 WHERE `index_releaseId` = t1.`index_releaseId` AND `index_value` LIKE '%Scarlet%') AND EXISTS(SELECT 1 FROM table1 WHERE `index_releaseId` = t1.`index_releaseId` AND `index_value` LIKE '%Witch%') AND EXISTS(SELECT 1 FROM table1 WHERE `index_releaseId` = t1.`index_releaseId` AND `index_value` LIKE '%WandaVision%')
 |  index_releaseId |  |:-------------- |  |  10001 | 

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM