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.

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

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛