HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Help with Query. Finding records that have the same relationships (MySQL)

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
samethewithrecordsqueryhelpmysqlthatfindingrelationships

Problem

I have a table of Listings that has a many to many relationship with a Taxons table. The table structure looks like this:

listings
----------------
id (int)
name (varchar)

listings_taxons
----------------
listing_id (int)
taxon_id (int)

taxons
----------------
id (int)
name (varchar)


My goal is to select all rows in the listings table that has a matching list of taxon ids. Each returned listing record must have a relationship with the two taxons, such that I get the record set containing the intersection of records between the two taxons.

Example: I have a listing called "Muffler" and it has the following taxons: "Ford", "Mustang", "Exhaust". If I query for all listings with "Ford" and "Exhaust" I should get all listings that have "Ford" and "Exhaust" as taxons.

How would I construct this query efficiently?

Solution

If I understand correctly, you want to perform relational-division. Try this question with lots of different ways to accomplish that: How to filter SQL results in a has-many-through relation.

I would go for the (multiple) JOIN solution but you can always test with your data and queries:

SELECT 
    li.*

FROM
    listings AS li

  JOIN
    listings_taxons AS lt1
      ON  lt1.listing_id = li.id
  JOIN
    taxons AS t1 
      ON  t1.id = lt1.taxon_id
      AND t1.name = 'Ford'

  JOIN
    listings_taxons AS lt2
      ON  lt2.listing_id = li.id
  JOIN
    taxons AS t2 
      ON  t2.id = lt2.taxon_id
      AND t2.name = 'Exhaust'

Code Snippets

SELECT 
    li.*

FROM
    listings AS li

  JOIN
    listings_taxons AS lt1
      ON  lt1.listing_id = li.id
  JOIN
    taxons AS t1 
      ON  t1.id = lt1.taxon_id
      AND t1.name = 'Ford'

  JOIN
    listings_taxons AS lt2
      ON  lt2.listing_id = li.id
  JOIN
    taxons AS t2 
      ON  t2.id = lt2.taxon_id
      AND t2.name = 'Exhaust'

Context

StackExchange Database Administrators Q#14391, answer score: 2

Revisions (0)

No revisions yet.