我将如何结合这两个查询?

时间:2012-03-27 03:12:31

标签: 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");

它从我的数据库收集我的所有歌曲和相关的favorite信息。

这是一个基本的分页查询,它按天数组返回我的数据库中的值:

$query = mysql_query("
        select * from songs t1 join (
        select to_days(date) day from songs 
        group by day 
        order by day desc 
        limit $start_row, $items_per_page
        ) t2
        on to_days(t1.date) = t2.day
        order by day desc") or die(mysql_error());

以下是两个表songsfavorites

的列信息

歌曲:songs schema

收藏夹:favorites schema

收藏夹和歌曲之间的相关性非常简单,其中favorite中的favorites值包含了它最喜欢的歌曲的唯一id

我的问题是如何将这两个查询组合起来,以便返回原始查询中的所有信息,但在第二个查询中进行分组和分页?

2 个答案:

答案 0 :(得分:0)

我不使用MySQL而不熟悉使用“限制”,但这个脚本可能有用。带收藏夹的LEFT JOIN不应增加行数并附加列。 “限制”是否也适用于外部脚本?

select s.*,UNIX_TIMESTAMP(`date`) AS `date`, f.userid as favoritehash  
from   songs s 
       join (
              select to_days(date) day 
              from songs 
              group by to_days(date) 
              order by day desc
              limit $start_row, $items_per_page
             ) s2  on to_days(s.date) = s2.day
    LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash'

答案 1 :(得分:0)

SELECT B.* 
FROM favorites as A
JOIN ( 
    select * from songs t1 join (
        select to_days(date) day from songs 
        group by day 
        order by day desc 
        limit $start_row, $items_per_page
        ) t2
        on to_days(t1.date) = t2.day
        order by day desc
) as B
ON A.Favorite = B.ID
ORDER BY B.DAY, B.ID