如何使用具有可选值的多个条件从Mysql表中获取值

问题描述 投票:0回答:3

我需要从多个条件中检索MYSQL表中的所有数据,但这里有一些输入是可选的。我在解释下面的表格。

db_exam:

id   name   reg_no     zone    center    college    sub_code  

1    aaa      12         3       AB        scs          2

2    bbb      12         2       AB        BJB           2

3    ccc      13         3       AB        BJB          3    

我传递以下输入来获取所有数据。

reg_no=12
zone=3
center=AB
sub_code=2

从上面的输入中,一些是可选的意味着列center and sub_code的值可能在那里或可能是空白的。在这里,我需要使用上述条件以及列center=AB or center=''sub_code=2 or sub_code=''的值来查询所有数据。但前两个条件是强制性的。

php mysql
3个回答
0
投票

使用以下查询

select * from db_exam where reg_no=12 and zone=3 and (center=AB or center='') and (sub_code=2 or sub_code='')

0
投票

用户在哪里IN查询如下。传递输入值和默认值,如空字符串''。

SELECT * 
FROM db_exam
WHERE (reg_no = <number> AND zone= <number> AND center IN (<input>, '') AND sub_code IN (<input>, ''));

如果我错了,请纠正我。


0
投票

试试这个:

    SELECT
        t1.id
       ,t1.name
       ,t1.reg_no
       ,t1.zone
       ,t1.college
       ,t2.center
       ,t3.sub_code
    FROM db_exam t1
    INNER JOIN db_exam t2
    ON t2.id=t1.id
    AND t2.center='AB'
    INNER JOIN db_exam t3
    ON t3.id=t1.id
    AND t3.sub_code=2;
© www.soinside.com 2019 - 2024. All rights reserved.