mysql year java_How to deselect current year in MYSQL

可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:

问题:

So I have this problem of selecting the years that are inside my database. I have existing years from 2015 to 2019. I have to remove the current year.. I'm using this method YEAR(CURDATE()) but I can't seem to use of properly.

//This is the PHP code that I use to get the years existing and throw it in the option input

session_start();

require_once 'connection.php';

$output = "";

$query = "(SELECT DISTINCT DATE_FORMAT(`date_happened`,'%Y') AS year FROM `tbl_flood_info`)

UNION

(SELECT DISTINCT DATE_FORMAT(`date_happened`,'%Y') AS year FROM `tbl_fire_info`)

UNION

(SELECT DISTINCT DATE_FORMAT(`date_happened`,'%Y') AS year FROM `tbl_accident_info`)

UNION

(SELECT DISTINCT DATE_FORMAT(`date_happened`,'%Y') AS year FROM `tbl_crime_info`)

ORDER BY year DESC";

$result = mysqli_query($connection, $query);

$numrows = mysqli_num_rows($result);

$x = 0;

if ($numrows > 0) {

while($row = mysqli_fetch_assoc($result)){

$output .= "" .$row['year']. "";

$x++;

}

}

echo $output;

mysqli_close($connection);

?>

//The ajax code to get the values from the PHP file

$.ajax({

type: "post",

url: "../get_year.php",

success: function(data) {

$("#selectYear").append(data.trim());

getFilter();

}

});

回答1:

You can try like below -

SELECT DATE_FORMAT(`date_happened`,'%Y') AS year FROM `tbl_flood_info`

where year(`date_happened`)

UNION

SELECT DATE_FORMAT(`date_happened`,'%Y') AS year FROM `tbl_fire_info` where year(`date_happened`)

UNION

SELECT DATE_FORMAT(`date_happened`,'%Y') AS year FROM `tbl_accident_info` where year(`date_happened`)

UNION

SELECT DATE_FORMAT(`date_happened`,'%Y') AS year FROM `tbl_crime_info` where year(`date_happened`)

ORDER BY year DESC"

回答2:

I would use the year() function instead of converting to a string:

SELECT year

FROM ((SELECT year(date_happened) as year

FROM `tbl_flood_info`

) UNION

(SELECT year(date_happened) as year

FROM `tbl_fire_info`

) UNION

(SELECT year(date_happened) as year

FROM `tbl_accident_info`

) UNION

(SELECT year(date_happened) as year

FROM `tbl_crime_info`

)

) t

WHERE year < YEAR(CURDATE());

UNION removes duplicates so all the SELECT DISTINCTs are unnecessary.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值