简体   繁体   English

将两个MYSQL查询合并为一个查询

[英]Combining two MYSQL Queries into a single one

I am trying to combine two MYSQL Queries into one. 我正在尝试将两个MYSQL查询合并为一个。 What I want to do is select the first and last row added for each day and subtract the last column for that day from the first column of that day and output that. 我想做的是选择每天添加的第一行和最后一行,然后从当天的第一列中减去该天的最后一列,然后输出。 What this would do is give me a net gain of XP in this game for that day. 这将为我带来当天那场比赛的XP净收益。

Below are my two queries, their only difference is ordering the date by DESC vs ASC. 以下是我的两个查询,它们的唯一区别是按DESC与ASC排序日期。 the column in the database that i want to subtract from each other is "xp" 我要互相减去的数据库中的列是“ 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')


                "); 
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

This assumes that XP always increases, so it doesn't need to use the times to find the beginning and ending values. 假设XP一直在增加,因此不需要使用时间来查找开始和结束值。

If that's not a correct assumption, what you want is something like this: 如果这不是正确的假设,那么您想要的是这样的:

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

Replace subquery1 with a query that returns the first row of each day, and subquery2 with a query that returns the last row of each day. subquery1替换为返回每天第一行的查询,将subquery2替换为返回每天最后一行的查询。 The queries you posted in your question don't do this, but there are many SO questions you can find that explain how to get the highest or lowest row per group. 您在问题中发布的查询不会执行此操作,但是您可以找到许多SO问题,这些问题说明了如何获得每个组的最高或最低行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM