douniuta4783 2014-03-28 04:58
浏览 152
已采纳

高级搜索3个字段,需要查询

I have an advanced search form with three fields. The user can use anyone of the fields or any two or all fields to begin a search. so I want to check whether the user entered a value for a particular field and write queries according to the values presented through a series of if loop. But I'm curious to know whether is there any equvailent technique in mysql to avoid the if loops and achive the search in single query.?

the following is the sample of checking user input.

if($school!="" & $district1!="" & $scl_type!="")
{
    echo "3 fields available";
}
else if($school=="" & $district1!="" & $scl_type!="")
{
    echo "school empty, district,schooltype available";
}
else if($school!="" & $district1=="" & $scl_type!="")
{
    echo "school,school type available district empty";
}
else if($school!="" & $district1!="" & $scl_type=="")
{
    echo "school,district only present,school type is empty";
}

.....

so I write different queries in each if statement. Is there any shortcut?

<----UPDATE:---> I got this query, it works fine. but when two schools available in the same district it returns only one. it returns only one result even many result is available, what to do?

SELECT * FROM `register` WHERE 
    (schoolname IS NULL OR schoolname LIKE '%national%') 
            AND 
    (schooltype IS NULL OR schooltype LIKE '%state board%') 
            AND 
    (district IS NULL OR district LIKE '%thiruvarur%');
  • 写回答

6条回答 默认 最新

  • dpn517111 2014-03-28 05:15
    关注

    Your parameters - @school,@schooltype,@district

    select items from yourtable where 
        (school like @school) 
            and 
        (schooltype like @schooltype) 
            and 
        (district like @district)
    

    while passing parameters if any field is empty, make corresponding parameter = '%%' , for any entered fields, make corresponding parameter = "'" +enterdfieldtext +"'"

    example : in your second condition, the query will look like

    select * from table where  
        (school like '%%') 
            and 
        (schooltype like 'givenschooltype') 
            and 
        (district like 'givendistrict')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?