MySQL多个where子句动态生成

时间:2015-07-02 14:19:22

标签: mysql sql where

因此,用户可以通过

选择他想要过滤列表的类别数量

当只有一个项目被选中时,一切都很好:

        SELECT SQL_CALC_FOUND_ROWS a.id, a.PAnr, b.family, b.articlenr, b.ratio, a.oiltype, a.oiltemp
        FROM testdata_test a, testdata_gear b
        WHERE a.id = b.test_id  AND b.family = 'R660' 
        ORDER BY a.PAnr desc
        LIMIT 0, 10

但是当用户添加更多内容时:

        SELECT SQL_CALC_FOUND_ROWS a.id, a.PAnr, b.family, b.articlenr, b.ratio, a.oiltype, a.oiltemp
        FROM testdata_test a, testdata_gear b
        WHERE a.id = b.test_id  AND b.family = 'R540' OR  b.family = 'R660' 
        ORDER BY a.PAnr desc
        LIMIT 0, 10

当没有AND部分的桌子大约4000时,我得到大约400万次点击。如果用户选择另一个,则大约有800万次点击。 我错过了什么?

2 个答案:

答案 0 :(得分:2)

将您的查询更改为此,您的查询将不会按预期运行OR语句,

SELECT SQL_CALC_FOUND_ROWS a.id, a.PAnr, b.family, b.articlenr, 
        b.ratio, a.oiltype, a.oiltemp
        FROM testdata_test a, testdata_gear b
        WHERE a.id = b.test_id  AND (b.family = 'R540' OR  b.family = 'R660')
        ORDER BY a.PAnr desc
        LIMIT 0, 10

或者

SELECT SQL_CALC_FOUND_ROWS a.id, a.PAnr, b.family, b.articlenr, 
        b.ratio, a.oiltype, a.oiltemp
        FROM testdata_test a, testdata_gear b
        WHERE a.id = b.test_id  AND b.family IN ('R540','R660')
        ORDER BY a.PAnr desc
        LIMIT 0, 10

答案 1 :(得分:1)

您正在混合andor条款而没有(),因此您正在有效地运行:

WHERE ((a.id = b.test_id) AND (b.family = 'R540')) 
   OR (b.family = 'R660')

请注意()的定位方式。

你可能想要

WHERE (a.id = b.test_id) AND (b.family IN ('R540', 'R660'))