dpus81500574 2014-08-20 19:44
浏览 42
已采纳

获取多行的年份部分

I have a SQL table called "picturevents". In there are all events stored to which pictures exist.

I would now like to implement a dropdown on my page, where the user can select the year from which he would like to have the pictures displayed. For this I need to receive all years from my database.

I now have the following function in my php script (which works perfectly fine):

function getPictureYears(){

    $ret = mysqli_query($this->link, "SELECT `id` FROM `pictureevents` WHERE 1");
    $array = null;
    while($row = mysqli_fetch_array($ret, MYSQL_ASSOC)){
        $array[] = $row;
    }

    for($i=0; $i < sizeof($array); ++$i){
        $id = $array[$i]['id'];
        $array[$i]["year"] = mysqli_fetch_row(mysqli_query($this->link, "SELECT EXTRACT(YEAR FROM ( SELECT `date` FROM `pictureevents` WHERE `id` = $id))"))[0];
    }
    return $array;  
}

I would be happy if I could simplify it. I found the following function:

SELECT EXTRACT(YEAR FROM (SELECT `date` FROM `pictureevents` WHERE 1))

This works great as long as the subquery only returns one row, when there is more than one row in the table, SQL reports:

     1242 - Subquery returns more than 1 row 

How can I get around the error, but still doing everything "in SQL"? Is it even possible?

BTW: The reason why I always try to do as much as possible in SQL is: their code is much more sophisticated than what I could ever write and it simplifies my code very much.

  • 写回答

1条回答 默认 最新

  • dpcj32769 2014-08-20 19:46
    关注
    SELECT distinct year(`date`) FROM `pictureevents`
    

    Returns all years (every year once) for which entries in pictureevents exist.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题