Filtering EAV table with multiple conditions

后端 未结 2 1970
抹茶落季
抹茶落季 2021-01-13 19:24

I have 2 tables:

Table objects:

object_id | object_group_id

Table attributes:

attr_id | a         


        
相关标签:
2条回答
  • 2021-01-13 20:01

    After couple hours of combining and trying, I finally did:

        SELECT * FROM objects as o
    
    /* filter1 join */
    INNER JOIN 
        attributes AS f1 
            ON 
        o.object_id = f1.attr_object_id 
            AND 
        f1.attr_property_id = 1
            AND
        f1.attr_value <= '100000'
    
    /* filter2 join */
    INNER JOIN 
        attributes AS f2 
            ON 
        f1.attr_object_id = f2.attr_object_id 
            AND 
        f2.attr_property_id = 2
            AND
        f2.attr_value > '2000'
    
    WHERE 
        o.object_group_id = 1
    

    I was too close, and done this by moving all filter conditions to INNER JOIN.

    0 讨论(0)
  • 2021-01-13 20:13

    Try this. I am not sure why do you have the last lines

    SELECT
      o.object_id, o.object_group_id,
      f1.attr_value AS val1,
      f2.attr_value AS val2,
    FROM objects AS o
    LEFT JOIN attributes f1 ON o.object_id = f1.attr_object_id AND f1.attr_property_id = 1
    LEFT JOIN attributes f1 ON o.object_id = f2.attr_object_id AND f2.attr_property_id = 2
    WHERE
        o.object_group_id = 1
    AND
       f1.attr_value <= '100000'
    AND
       f2.attr_value > '2000';
    

    remove this lines and test it also

    AND
       f1.attr_value <= '100000'
    AND
       f2.attr_value > '2000';
    
    0 讨论(0)
提交回复
热议问题