SQL从匹配查询的另一行中查找上一个日期

时间:2013-08-01 23:32:56

标签: php sql date

这是我加入的两张桌子......

song_id   song_name
  51  |  Song Name A
  368 |  Song Name B
  168 |  Song Name C
  568 |  Song Name D
  13  |  Song Name E


song_id | song_order|        show_date      |show_id
368     |     1     |  2010-02-17 00:00:00  |  367      
368     |     0     |  2012-04-06 00:00:00  |  499 
51      |     2     |  2012-01-19 00:00:00  |  399
51      |     2     |  2013-04-24 00:00:00  |  870 
51      |     8     |  2013-07-19 00:00:00  |  899 
368     |     2     |  2013-07-19 00:00:00  |  899 
13      |     5     |  2013-07-19 00:00:00  |  899 
568     |     2     |  2013-07-19 00:00:00  |  899
368     |     4     |  2012-06-08 00:00:00  |  799 
168     |     2     |  2013-06-28 00:00:00  |  896 
568     |     2     |  2013-07-03 00:00:00  |  897 
568     |     2     |  2010-02-21 00:00:00  |  897 

我已经解决了我在SQL Fiddle link上想要做的事情,但我无法正确使用代码。我正在尝试基于show_id的值说'899',返回所有等于899的行,show_ids都有相同的日期分配给它们,但根据歌曲ID我想返回song_id的前一个日期过来。

我希望数据返回...

  SHOW_DATE    | SHOW_ID |   SONG_NAME | SONG_ID |     PREVDATE   
July, 19 2013  |     899 | Song Name A |      51 | April, 24 2013 
July, 19 2013  |     899 | Song Name B |     368 | April, 08 2012 
July, 19 2013  |     899 | Song Name E |      13 | FIRST TIME 
July, 19 2013  |     899 | Song Name D |     568 | July, 03 2013

我的代码只是返回2013年7月19日之前的日期,即2013年7月3日,并为每个PrevDate提供。谁能帮助我?我不是最有经验的编码员,我相信我不能做我在这里所做的事情,因为我正在分组一个子查询。先谢谢!

 SELECT tbl_shows.show_date, tbl_shows.show_id, 
 tbl_songs.song_name, tbl_shows.song_id, (
    SELECT
        MAX(show_date)
    FROM tbl_shows AS fdate
    WHERE tbl_shows.show_date > show_date 
 ) As PrevDate
  FROM tbl_shows LEFT JOIN tbl_songs
  ON tbl_shows.song_id = tbl_songs.song_id
  WHERE tbl_shows.show_id = 899

2 个答案:

答案 0 :(得分:1)

看起来你只需告诉MySQL按日期对结果进行分组:

SELECT tbl_shows.show_date, tbl_shows.show_id, 
tbl_songs.song_name, tbl_shows.song_id, (
   SELECT
       MAX(show_date)
   FROM tbl_shows AS fdate
   WHERE tbl_shows.show_date > show_date 
) As PrevDate
FROM tbl_shows LEFT JOIN tbl_songs
ON tbl_shows.song_id = tbl_songs.song_id
GROUP BY tbl_shows.show_date
HAVING tbl_shows.show_id = 899

编辑:或者,正如Dan Bracuk指出的那样,你可以这样做:

SELECT tbl_shows.show_date, tbl_shows.show_id, 
tbl_songs.song_name, tbl_shows.song_id, (
   SELECT
       MAX(show_date)
   FROM tbl_shows AS fdate
   WHERE tbl_shows.show_date > show_date 
) As PrevDate
FROM tbl_shows
LEFT JOIN tbl_songs
ON tbl_shows.song_id = tbl_songs.song_id
WHERE tbl_shows.show_id = 899
GROUP BY tbl_shows.show_date
ORDER BY tbl_shows.show_id DESC
LIMIT 0, 10

注意:最后两行更像是一个例子。

答案 1 :(得分:0)

试试这个......

  SELECT a.show_date, a.show_id, 
  b.song_name, a.song_id, (
  SELECT
    MAX(show_date)
  FROM tbl_shows AS c
  WHERE a.show_date > c.show_date and a.song_id = c.song_id
  ) As PrevDate
  FROM tbl_shows a, tbl_songs b
  WHERE a.song_id = b.song_id
  AND a.show_id = 899