将两个MYSQL查询合并为一个

时间:2013-12-13 06:58:19

标签: php mysql sql

我正在尝试将两个MYSQL查询合并为一个。我想要做的是选择每天添加的第一行和最后一行,并从当天的第一列中减去当天的最后一列并输出。这样做会让我在当天的游戏中获得XP的净收益。

以下是我的两个问题,他们唯一的区别是通过DESC和ASC订购日期。我希望相互减去的数据库中的列是“xp”

$query = mysql_query("

                SELECT * FROM (SELECT  * FROM skills WHERE
                userID='$checkID' AND
                        skill = '$skill' AND
                        date >= ".$date."
                ORDER BY date DESC) as temp
                GROUP BY from_unixtime(date, '%Y%m%d')


                ");

                $query2 = mysql_query("

                SELECT * FROM (SELECT  * FROM skills WHERE
                userID='$checkID' AND
                        skill = '$skill' AND
                        date >= ".$date."
                ORDER BY date DESC) as temp
                GROUP BY from_unixtime(date, '%Y%m%d')


                "); 

1 个答案:

答案 0 :(得分:0)

SELECT FROM_UNIXTIME(date, '%Y%m%d') AS YYYYMMDD, MAX(xp)-MIN(xp) AS xp_gain
FROM skills
WHERE userID = '$checkID'
AND skill = '$skill'
AND date >= $date
GROUP BY YYYYMMDD

这假设XP总是增加,因此不需要使用时间来查找开始值和结束值。

如果这不是一个正确的假设,你想要的是这样的:

SELECT first.YYYYMMDD, last.xp - first.xp
FROM (subquery1) AS first
JOIN (subquery2) AS last
ON first.YYYYMMDD = last.YYYYMMDD

subquery1替换为返回每天第一行的查询,将subquery2替换为返回每天最后一行的查询。您在问题中发布的查询不会执行此操作,但您可以找到许多SO问题,解释如何获得每组最高或最低的行。