素材牛VIP会员
mysql如何查询存储两种格式的字段并添加过滤条件?
 路***6  分类:PHP代码  人气:816  回帖:3  发布于6年前 收藏

如何查询存储两种格式的字段并为每种情况添加过滤条件?

字段名分别为type和salary

如何查询出type=1,salary只有两位是大于06的或是一个薪资区间,横杠(-)前面的大于8000的数据?

目前可以写出的sql:

 select * from test where type = 1 and (salary > '06' or salary > '8000') order by issuedate desc limit 10
这样无法正确查出数据

 标签:mysqlphp

讨论这个帖子(3)垃圾回帖将一律封号处理……

Lv5 码农
飞***a 交互设计师 6年前#1
select * 
from test 
where type = 1 
and ((salary > '06' and length(salary) = 2) or salary > '8000')) 
order by issuedate desc limit 10
Lv6 码匠
bo***18 产品经理 6年前#2

先看下这两个SQL:

SELECT
    IF(
        POSITION('-' IN '8000-16000'),
        SUBSTR('8000-16000' FROM 1 FOR POSITION('-' IN '8000-16000') - 1),
        'XX-TYPE'
    );
SELECT
    IF(
        POSITION('-' IN '06'),
        SUBSTR('06' FROM 1 FOR POSITION('-' IN '06') - 1),
        'XX-TYPE'
    );

按照这个思路,来写你的SQL:

SELECT
    *
FROM
    test
WHERE
    type = 1 AND
    (
        (
            POSITION('-' IN salary)
            AND
            SUBSTR(salary FROM 1 FOR POSITION('-' IN salary) - 1) > 8000
        ) OR (
            POSITION('-' IN salary) = 0
            AND
            salary > 6
        )
    )
ORDER BY
    issuedate DESC
LIMIT 10;

由于,SQL对于数字类型判断不是很严格,所以可以直接写6和8000,不需要强制写字符串。

当然,不能否认楼上的substring_index是更好更便捷的解决方案。

Lv3 码奴
空***子 职业无 6年前#3
substring_index(salary, '-', 1) > '06' or substring_index(salary, '-', 1) > '8000'
 文明上网,理性发言!   😉 阿里云幸运券,戳我领取