这是我的原始查询:
$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");
建议?
答案 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 JOIN
是FROM
中表格列表的一部分,您不能拥有条件。