简体   繁体   English

mysql 在逗号分隔符字段上仅选择当前年份和最大年份之间的字段

[英]mysql select only fields between range current year and max year on comma separator field

I have this field on table that stores years with comma separator and I'm looking for a way to filter results containing years between range of current year and max year from field, this is what I got so far:我在表格上有这个字段,它用逗号分隔符存储年份,我正在寻找一种方法来过滤包含当前年份范围和字段中最大年份之间的年份的结果,这就是我到目前为止得到的结果:

SELECT *, max(SUBSTRING_INDEX(years, ',', -1)) as maxyear from availability WHERE CONCAT(",", years, ",") REGEXP ",(2022|2023|2024)," GROUP BY id

years are manually inserted in REGEXP, need them to be dynamic, the maxyear in select gets the max year on each result, test code below.年份是手动插入到 REGEXP 中的,需要它们是动态的,select 中的maxyear获取每个结果的最大年份,下面的测试代码。

FIDDLE: http://sqlfiddle.com/#!9/ffaed2/1小提琴: http ://sqlfiddle.com/#!9/ffaed2/1

Having multiple values in a column means that your database is not even first normal form (1NF) .一列中有多个值意味着您的数据库甚至不是第一范式 (1NF) The reason why this is to be avoided is demonstrated by your very question.您的问题证明了要避免这种情况的原因。

Your question is a bit vague.你的问题有点含糊。 You say, "I'm looking for a way to filter results containing years between range of current year and max year from field."你说,“我正在寻找一种方法来过滤包含当前年份范围和字段中最大年份之间的年份的结果。” The current year is 2022 and the "max year from field" would be 2027 based on the data you supplied, so you should return 3 rows.当前年份是 2022 年,根据您提供的数据,“字段的最大年份”将为 2027 年,因此您应该返回 3 行。 But this is equivalent to saying you want to filter results containing years >= the current year.但这相当于说您要过滤包含年份> =当前年份的结果。 In that case the following should work:在这种情况下,以下应该起作用:

Try:尝试:

SELECT *, SUBSTRING_INDEX(years, ',', -1) as maxyear FROM availability
WHERE SUBSTRING_INDEX(years, ',', -1) >= YEAR(CURDATE())

But if the "max year" is a year to be supplied, for example 2024, then:但如果“最大年份”是要提供的年份,例如 2024 年,则:

SELECT *, SUBSTRING_INDEX(years, ',', -1) as maxyear FROM availability
WHERE SUBSTRING_INDEX(years, ',', -1) between YEAR(CURDATE()) and 2024

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM