Mysql
 sql >> база данни >  >> RDS >> Mysql

WHERE LIKE с множество ключови думи

Преосмислих и може би този подход е по-добър:

SELECT T1.id
FROM 
(  
select textures.id 
from textures
WHERE textures.name LIKE '%texture1%' 
UNION 
select textures.id 
from textures
join category_texture on category_texture.texture_id = textures.id
join categories on categories.id = category_texture.category_id
WHERE categories.name LIKE '%texture1%'
UNION
select textures.id 
from textures
join tag_texture on tag_texture.texture_id = textures.id
join tags on tags.id = tag_texture.tag_id
WHERE tags.name LIKE '%texture1%'
UNION 
select textures.id 
from textures
join size_texture on size_texture.texture_id = textures.id
join sizes on sizes.id = size_texture.size_id 
WHERE sizes.name LIKE '%texture1%'
) AS T1
JOIN 
(  
select textures.id 
from textures
WHERE textures.name LIKE '%category2%' 
UNION 
select textures.id 
from textures
join category_texture on category_texture.texture_id = textures.id
join categories on categories.id = category_texture.category_id
WHERE categories.name LIKE '%category2%'
UNION
select textures.id 
from textures
join tag_texture on tag_texture.texture_id = textures.id
join tags on tags.id = tag_texture.tag_id
WHERE tags.name LIKE '%category2%'
UNION 
select textures.id 
from textures
join size_texture on size_texture.texture_id = textures.id
join sizes on sizes.id = size_texture.size_id 
WHERE sizes.name LIKE '%category2%'
) AS T2
ON T1.id = T2.id
JOIN
(  
select textures.id 
from textures
WHERE textures.name LIKE '%tag3%' 
UNION 
select textures.id 
from textures
join category_texture on category_texture.texture_id = textures.id
join categories on categories.id = category_texture.category_id
WHERE categories.name LIKE '%tag3%'
UNION
select textures.id 
from textures
join tag_texture on tag_texture.texture_id = textures.id
join tags on tags.id = tag_texture.tag_id
WHERE tags.name LIKE '%tag3%'
UNION 
select textures.id 
from textures
join size_texture on size_texture.texture_id = textures.id
join sizes on sizes.id = size_texture.size_id 
WHERE sizes.name LIKE '%tag3%'
) AS T3
ON T1.id = T3.id

Просто добавете повече/по-малко JOIN...ON T1.id = Tn.id секции, които да отговарят на вашите параметри.

Ето една цигулка, която показва как се изпълнява:http://sqlfiddle.com/#!9/ 9abe6/1



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. MySQL използва сортиране на файлове в индексирана колона TIMESTAMP

  2. MySQL Вмъкване на Gson дата

  3. Сложен SQL SELECT за изчисляване на рейтинг на една колона

  4. Yii2:Как да напиша отделна SQL заявка?

  5. Правете закъснение / цикъл, за да получите 10 произволни резултата