Warm tip: This article is reproduced from serverfault.com, please click

MySQL: Taxonomy

发布于 2020-11-30 16:46:41

I was hoping someone could help me come up with a query for what I'm looking to do. I have a website that lists game servers and I'm trying to improve my search system a bit.

There's three tables of interest; servers, version_taxonomy and category_taxonomy. The taxonomy tables contain two columns, one for a server ID and one for a version/category ID, where associations between a server and it's supported versions and categories can be made.

Up till now, I've been joining both taxonomy tables to the server table and be looking up servers for one version and one category, it's been working fine. However I'm looking to allow the search of a server that has multiple categories at the same time.

I've made an image to try and illustrate what I'm looking to do: taxonomy tables

Say I'm looking for a server that has both categories 5 and 12 - Based on the table on the left that would be servers 1 and 3. But how would that be in a query? And how would I use that query to later get and work with the rest of the server data (JOIN like I'd normally do?)

Hopefully that makes sense! Looking forward to your responses.

Questioner
Stelios Mac
Viewed
0
xQbert 2020-12-01 01:02:08

Assuming I understand the question:

Join the two tables then count the distinct values of category ID while limiting by them. Distinct is not be needed if you can guarantee the uniqueness of serverID, categoryID from table A and a 1:1 relationship to server taxonomy which would be true if you always limit by 1 and only 1 version...

SELECT A.ServerID, count(A.CategoryID) CatCnt
FROM A
INNER JOIN B
  on A.ServerID = B.ServerID
WHERE A.CATEGORYID in (5,12)
  and B.Version= 1.16
GROUP BY A.ServerID
HAVING count(distinct A.CategoryID) = 2

The category ID could be parameter passed in as well as the count distinct as you know both values.

This could be used as a CTE or as a inline derived table as a source then join in to get the addiontal data; or left join in the desired data assuming it's a 1:1 relationship.

If you want a working example: post DDL for table and SQL to create sample data and I'll put something in https://rextester.com/.