Skip to content

Instantly share code, notes, and snippets.

@gmaggio
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmaggio/03160b2ac730f10930dc to your computer and use it in GitHub Desktop.
Save gmaggio/03160b2ac730f10930dc to your computer and use it in GitHub Desktop.
[SQL] Related Posts by Relevancy. Source: http://stackoverflow.com/a/11144559/851045
# Note: Higher number equals higher priority
# to indicate greater relevancy
SELECT *,
(CASE WHEN attribute1_field = attribute1_value THEN 2 ELSE 0 END) +
(CASE WHEN attribute2_field = attribute2_value THEN 1 ELSE 0 END) +
(CASE WHEN attribute3_field = attribute3_value THEN 1 ELSE 0 END) AS priority
FROM table_post
WHERE (
attribute1_field = attribute1_value
OR attribute2_field = attribute2_value
OR attribute3_field = attribute3_value
)
ORDER BY priority DESC
LIMIT 0 , 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment