需要为复杂查询添加过滤器

时间:2016-04-14 14:39:52

标签: php mysql

我正在尝试编写一个查询,它将帮助我从db中恢复类,批处理和机构详细信息 到目前为止,我已成功完成了以下工作:

SELECT
    gallery.path_url AS insimage,
    r3.*
FROM
    gallery
INNER JOIN (
    SELECT
        institution.id AS insid,
        institution.ProfileImageID,
        institution.`name` AS insname,
        institution.Locality AS inslocality,
        institution.RegistrationFee AS ins_reg_fee,
        institution.IsTrail AS ins_is_trail,
        institution.LatLong AS latlong,
        r2., activity.`name` AS activityname
    FROM
        institution
    INNER JOIN (
        SELECT
            class., count() AS batch_count,
            r1.
        FROM
            class
        INNER JOIN (
            SELECT
                batch.ID AS batch_id,
                batch.ClassID AS class_id,
                batch.LevelID AS level_id,
                batch.agegroupID AS agegroup_id,
                count(*) AS num_batches,
                min(Price) AS min_price,
                max(Price) AS max_price
            FROM
                batch,
                batchstarttimes
            WHERE
                batch.ID = batchstarttimes.BatchID
            AND batchstarttimes.StartTime BETWEEN '" . $sttime . "'
            AND '" . $endtime . "'
            GROUP BY
                batch.ID
        ) AS r1
        WHERE
            r1.class_id = class.ID
        GROUP BY
            r1.class_id
    ) AS r2 ON r2.institutionid = institution.id
    INNER JOIN activity ON activity.id = r2.activityid
    WHERE
        activity.`name` LIKE '%" . $searchterm . "%'
    AND institution.Locality LIKE '%" . $locality . "%'
    AND institution.StatusID = 1
    AND level_id = 1
    AND agegroup_id = 5
) AS r3 ON r3.ProfileImageID = gallery.ID

当我尝试添加另外两个过滤器batch.LevelID和batch.agegroupID时,我陷入困境 任何方式我可以得到帮助或有人指向我的sql visualizr工具将有所帮助。

1 个答案:

答案 0 :(得分:0)

在WHERE子句中,替换:

AND level_id = 1
AND agegroup_id = 5

使用:

AND batch.LevelID = CASE WHEN " . $levelID . " = 0 THEN batch.LevelID ELSE " . $levelID . " END 
AND batch.agegroupID = CASE WHEN " . $ageGroupID . " = 0 THEN batch.agegroupID ELSE " . $ageGroupID . " END

关键是要将batch.LevelID和batch.agegroupID与自己进行比较,如果你想忽略它们进行过滤(这样他们总是如此)或者将它们与$levelID和{{进行比较1}}特定行的值。

此外,不建议在查询中直接使用变量,因为它容易受到SQL注入攻击。阅读准备好的陈述here