MySQL查找播放歌曲的上一个日期

时间:2013-08-19 23:34:02

标签: mysql date count

我正在寻找任何帮助,为什么我的代码不再适用。 SQL Fiddle指向ORIGINALMODIFIED代码的链接。 我将数据库放在两个不同的表中,这段代码运行正常。

SELECT DATE_FORMAT(a.show_date,'%m/%d/%y') as show_date, a.song_order, a.show_id, 
 b.song_name, a.song_id,  (
 SELECT 
 IFNULL(MAX(DATE_FORMAT(show_date,'%m/%d/%y')), 'NEW SONG')
 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

表格是:

CREATE TABLE tbl_songs
(`song_id` int, `song_name` varchar(11))
;

INSERT INTO tbl_songs
(`song_id`, `song_name`)
VALUES
(51, 'Song Name A'),
(368, 'Song Name B'),
(168, 'Song Name C'),
(568, 'Song Name D'),
(13, 'Song Name E')
 ;

 CREATE TABLE tbl_shows
(`song_id` int, `song_order` int, `show_date` datetime, `show_id` int)
 ;

 INSERT INTO tbl_shows
(`song_id`, `song_order`, `show_date`, `show_id`)
VALUES
    (51, 1, '2013-07-19 00:00:00', 899),
    (568, 2, '2013-07-19 00:00:00', 899),
    (168, 3, '2013-07-19 00:00:00', 899),
    (13, 4, '2013-07-19 00:00:00', 899),
    (368, 1, '2013-07-06 00:00:00', 898),
    (368, 1, '2013-07-03 00:00:00', 897),
    (368, 1, '2013-05-27 00:00:00', 896),
    (51, 1, '2013-04-10 00:00:00', 895),
(168, 1, '2013-04-10 00:00:00', 895),
(513, 1, '2013-03-12 00:00:00', 894),
(13, 1, '2013-03-03 00:00:00', 893);

为了让我的数据库更有效率,我不必一遍又一遍地重复日期,我将它分成另一个名为tbl_song_shows的表......就像这样。

 CREATE TABLE tbl_songs
(`song_id` int, `song_name` varchar(11))
 ;

 INSERT INTO tbl_songs
(`song_id`, `song_name`)
 VALUES
(51, 'Song Name A'),
(368, 'Song Name B'),
(168, 'Song Name C'),
(568, 'Song Name D'),
(13, 'Song Name E')
;

CREATE TABLE tbl_shows
(`song_id` int, `song_order` int, `show_date` datetime, `show_id` int)
;

INSERT INTO tbl_shows
(`show_date`, `show_id`)
VALUES
( '2013-07-19 00:00:00', 899),
( '2013-07-19 00:00:00', 899),
( '2013-07-19 00:00:00', 899),
( '2013-07-19 00:00:00', 899),
( '2013-07-06 00:00:00', 898),
( '2013-07-03 00:00:00', 897),
( '2013-05-27 00:00:00', 896),
( '2013-04-10 00:00:00', 895),
( '2013-04-10 00:00:00', 895),
( '2013-03-12 00:00:00', 894),
( '2013-03-03 00:00:00', 893);

CREATE TABLE tbl_song_shows
(`song_id` int, `song_order` int, `show_id` int)
;

INSERT INTO tbl_song_shows
(`song_id`, `song_order`, `show_id`)
VALUES
 (51, 1, 899),
 (568, 2, 899),
 (168, 3, 899),
 (13, 4, 899),
 (368, 1, 898),
 (368, 1, 897),
 (368, 1, 896),
 (51, 1, 895),
 (168, 1, 895),
 (513, 1, 894),
 (13, 1, 893);

我更改了代码以反映附加表,但它不返回相同的查询数据。请参阅ORIGINALMODIFIED代码附带的两个SQL Fiddle链接。我正在寻找PrevDate来返回播放特定歌曲的上一个日期。在新代码中,它返回PrevDate但不基于歌曲。 任何帮助我恢复正常的帮助将不胜感激。谢谢。奖金如果之后有人可以告诉我如何计算Show_Date和PrevDate之间的节目。 谢谢!!!

0 个答案:

没有答案
相关问题