MySQL: Query and join two tables

前端 未结 4 1765
灰色年华
灰色年华 2021-01-23 03:17

I have two tables that I believe I want to JOIN. I\'m very new to this and am not completely sure…

The first table is called venues with the variables <

4条回答
  •  生来不讨喜
    2021-01-23 04:11

    You want to find venues that match conditions in two rows in table venue_terms. This can be accomplished by various methods. The most usual is by joining that table twice (another would be by a grouping query).

    Here's the first way. Join twice to the venue_terms table:

    SELECT v.id                                  --- whatever columns you need 
         , v.slug                                --- from the venues table
         , v.name
    FROM venues AS v
      INNER JOIN venue_terms AS vt1
        ON  vt1.venue = v.id
      INNER JOIN venue_terms AS vt2
        ON  vt2.venue = v.id
    WHERE ( vt1.option = 1 AND vt1.value = 10 )
      AND ( vt2.option = 2 AND vt2.value = 4 ) ;
    

    If you have 3 conditions, join thrice. If you have 10 conditions, join 10 times. It would be good for the efficiency of the query to have a compound index on (option, value, venue) in the terms table.

提交回复
热议问题