添加DATE_SUB以查询以返回mysql中的值范围

时间:2010-06-16 06:58:29

标签: php mysql

这是我的原始查询:

$query = mysql_query("SELECT s.*, UNIX_TIMESTAMP(`date`) AS `date`, f.userid as favoritehash FROM songs s LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash' ORDER BY s.date DESC");

这会返回我的数据库中的所有songs,然后从我的favorites表中加入数据,这样我就可以显示返回访问者点击过的最喜欢的项目。访问者可以通过cookie和favorites表中的唯一身份识别。

我需要更改此查询,以便我可以获得最后几个月的歌曲。以下是我尝试将DATE_SUB添加到我的查询中:

$query = mysql_query("SELECT s.*, UNIX_TIMESTAMP(`date`) AS `date`, f.userid as favoritehash FROM songs s WHERE `date` >= DATE_SUB( NOW( ) , INTERVAL 1 MONTH ) LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash' ORDER BY s.date DESC");

建议?

1 个答案:

答案 0 :(得分:1)

您只需移动WHERE子句:

SELECT
    s.*,
    UNIX_TIMESTAMP(`date`) AS `date`,
    f.userid as favoritehash
FROM
    songs s
    LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash'
WHERE `date` >= DATE_SUB( NOW( ) , INTERVAL 1 MONTH )
ORDER BY s.date DESC

LEFT JOINFROM中表格列表的一部分,您不能拥有条件。