选择包含4列中的1列中的值的数据

时间:2017-03-28 10:09:39

标签: mysql sql select

我想在SQL列'objekt1' OR 'objekt2' OR 'objekt3'或者'objekt4'。

这是我目前的查询:

$filter_objekt = "Lorem";

$ergebnis = mysqli_query($db, "SELECT * FROM aktionen WHERE 
            jahr LIKE '$filter_jahr' AND 
            kunde LIKE '$filter_kunde' AND 
            kampagne LIKE '$filter_kampagne' AND 
            objekt1 LIKE '$filter_objekt' OR 
            objekt2 LIKE '$filter_objekt' OR 
            objekt3 LIKE '$filter_objekt' OR 
            objekt4 LIKE '$filter_objekt' OR 
            mediamix LIKE '$filter_mediamix' AND 
            kosten LIKE '$filter_kosten' AND 
            schulnote LIKE '$filter_schulnote' AND 
            feedback_status LIKE '$filter_feedback' 
            ORDER BY kunde ASC, aktionsname ASC");

此时脚本会返回表的每一行,无论它是否包含'$ filter_objekt'的值。

非常感谢任何帮助。提前谢谢!

4 个答案:

答案 0 :(得分:1)

这是因为你需要括号

// Your code is similar to this:
WHERE A=$a AND B1=$x OR B2=$x OR B3=$x

// Which actually does this:
WHERE (A=$a AND B1=$x) OR (B2=$x) OR (B3=$x)

// And you want:
WHERE A=$a AND (B1=$x OR B2=$x OR B3=$x)

因此,在您的代码中,您只需在objekt

周围添加括号即可

答案 1 :(得分:1)

OR的优先级低于AND,因此您需要使用括号来应用所​​有AND条件和OR条件之一:

$ergebnis = mysqli_query($db, "SELECT * FROM aktionen WHERE 
            jahr LIKE '$filter_jahr' AND 
            kunde LIKE '$filter_kunde' AND 
            kampagne LIKE '$filter_kampagne' AND 
           (objekt1 LIKE '$filter_objekt' OR 
            objekt2 LIKE '$filter_objekt' OR 
            objekt3 LIKE '$filter_objekt' OR 
            objekt4 LIKE '$filter_objekt') AND /* I think you mean AND here, not OR, but I'm not 100% sure */ 
            mediamix LIKE '$filter_mediamix' AND 
            kosten LIKE '$filter_kosten' AND 
            schulnote LIKE '$filter_schulnote' AND 
            feedback_status LIKE '$filter_feedback' 
            ORDER BY kunde ASC, aktionsname ASC");

答案 2 :(得分:1)

您必须将4个OR的集合添加到带括号

的块中
.tcl

请注意,我将objekt4之后的OR更改为AND。

答案 3 :(得分:0)

试试这个

$ergebnis = mysqli_query($db, "SELECT * FROM aktionen WHERE 
        jahr LIKE '$filter_jahr' AND 
        kunde LIKE '$filter_kunde' AND 
        kampagne LIKE '$filter_kampagne' AND 
        (
        objekt1 LIKE '$filter_objekt' OR 
        objekt2 LIKE '$filter_objekt' OR 
        objekt3 LIKE '$filter_objekt' OR 
        objekt4 LIKE '$filter_objekt' )AND 
        mediamix LIKE '$filter_mediamix' AND 
        kosten LIKE '$filter_kosten' AND 
        schulnote LIKE '$filter_schulnote' AND 
        feedback_status LIKE '$filter_feedback' 
        ORDER BY kunde ASC, aktionsname ASC");