How to get the sum of previous 10 rows in mysql? - mysql

Is it possible to get the sum of values in last 10 rows with respect to the current row?
I have created a database for a shop, which contains a table named purchase_details. Structure of that table is:
+--------------------------------+---------------+-----+
| Field | Type | Key |
+--------------------------------+---------------+-----+
| Trans_ID | int(11) | PRI |
| Dealer_Name | varchar(40) | |
| Todays_Purchase | double(18,10) | |
| Total_Purchase_In_Last_10_Days | double(18,10) | |
+--------------------------------+---------------+-----+
Sample data:
+----------+-------------+-----------------+--------------------------------+
| Trans_ID | Dealer_Name | Todays_Purchase | Total_Purchase_In_Last_10_Days |
+----------+-------------+-----------------+--------------------------------+
| 1 | Rahul | 7769.1488285639 | NULL |
| 2 | Rahul | 4158.5117578537 | NULL |
| 3 | Rahul | 7200.1363099802 | NULL |
| 4 | Rahul | 9338.8341269511 | NULL |
| 5 | Rahul | 5897.7252866370 | NULL |
| 6 | Rahul | 3266.6656585172 | NULL |
| 7 | Rahul | 3188.0742696276 | NULL |
| 8 | Rahul | 4270.5917314234 | NULL |
| 9 | Rahul | 2604.3369713541 | NULL |
| 10 | Rahul | 7908.6014441989 | NULL |
| 11 | Rahul | 2693.4584823737 | NULL |
| 12 | Rahul | 7945.7825034862 | NULL |
| 13 | Rahul | 1904.1472157570 | NULL |
| 14 | Rajesh | 7093.0478540344 | NULL |
| 15 | Rajesh | 3219.3736989638 | NULL |
+----------+-------------+-----------------+--------------------------------+
I want get the sum of purchases done in last 10 transactions, with the condition that there should be at least 10 transactions to sum up.
Expected output:
+----------+-------------+-----------------+--------------------------------+
| Trans_ID | Dealer_Name | Todays_Purchase | Total_Purchase_In_Last_10_Days |
+----------+-------------+-----------------+--------------------------------+
| 1 | Rahul | 7769.1488285639 | 0.0000000000 |
| 2 | Rahul | 4158.5117578537 | 0.0000000000 |
| 3 | Rahul | 7200.1363099802 | 0.0000000000 |
| 4 | Rahul | 9338.8341269511 | 0.0000000000 |
| 5 | Rahul | 5897.7252866370 | 0.0000000000 |
| 6 | Rahul | 3266.6656585172 | 0.0000000000 |
| 7 | Rahul | 3188.0742696276 | 0.0000000000 |
| 8 | Rahul | 4270.5917314234 | 0.0000000000 |
| 9 | Rahul | 2604.3369713541 | 0.0000000000 |
| 10 | Rahul | 7908.6014441989 | 55602.6263900000 |
| 11 | Rahul | 2693.4584823737 | 50526.9360400000 |
| 12 | Rahul | 7945.7825034862 | 54314.2067800000 |
| 13 | Rahul | 1904.1472157570 | 49018.2176900000 |
| 14 | Rajesh | 7093.0478540344 | 0.0000000000 |
| 15 | Rajesh | 3219.3736989638 | 0.0000000000 |
+----------+-------------+-----------------+--------------------------------+
For this, I've created a mysql function, which will take the Trans_ID and Dealer_Name as a parameter, and will return the sum of Todays_Purchase column.
Function definition:
CREATE FUNCTION GET_TOTAL_PURCHASE(paramTransID INT, paramDealerName VARCHAR(40))
RETURNS DOUBLE(18,10)
READS SQL DATA
BEGIN
DECLARE totalPurchase DOUBLE(18,10);
SET totalPurchase = 0;
SELECT SUM(Todays_Purchase)
INTO totalPurchase
FROM purchase_details
WHERE Trans_ID > (paramTransID-10)
AND Trans_ID <= paramTransID
AND Dealer_Name = paramDealerName;
RETURN totalPurchase;
END
And the SQL query to update Total_Purchase_In_Last_10_Days column is:
UPDATE purchase_details
SET Total_Purchase_In_Last_10_Days = GET_TOTAL_PURCHASE(Trans_ID, Dealer_Name);
Above SQL works properly, but it takes too much time to execute. There are more than a million records in the table, so the query takes more than 5 minutes. Hoe to improve this?

Derived information (such as what you are asking for) is properly done in SELECTs, not by having redundant code in the table.
If one user pulls up his info, it will be reasonably cheap to compute the sum on the fly. And you already have the FUNCTION to do that.
However, can you really trust Trans_ID to be consecutive, no gaps, etc? Your nomenclature is inconsistent: "_Last_10_Days" vs "previous 10 rows" versus "Trans_". "10 days" can be tricky if there are gaps. Etc.

Related

MySQL to remove rows past the current date and transfer them to another table

I was tasked to create a database for a gym system for my project, I need help on what MySQL query should I use for my program.
First query: Remove rows in the TBL_ACTIVEMEMBER where the END column date is past the current date.
Second query: Transfer and insert those removed rows into another table which is TBL_INACTIVEMEMBER.
So these are my tables:
TBL_ACTIVEMEMBER:
+------+---------+--------+----------+----------+------------+------------+
| AMID | GYMID | INSTID | TYPE | TERM | START | END |
+------+---------+--------+----------+----------+------------+------------+
| 1 | 2021001 | 4502 | Gold | 3 Months | 2021-12-18 | 2022-03-18 |
| 2 | 2021003 | 4504 | Platinum | 3 Months | 2021-12-13 | 2022-03-13 |
| 3 | 2021002 | 4502 | Silver | 3 Months | 2022-01-15 | 2022-04-15 |
| 4 | 2021004 | 4502 | Platinum | 5 Months | 2021-12-25 | 2022-05-25 |
| 5 | 2021006 | 4503 | Silver | 5 Months | 2021-12-18 | 2022-05-18 |
| 6 | 2021007 | 4502 | Silver | 1 Month | 2021-12-24 | 2022-01-24 |
| 7 | 2021008 | 4501 | Gold | 3 Months | 2021-12-18 | 2022-03-18 |
| 8 | 2021008 | 4503 | Platinum | 1 Month | 2021-12-12 | 2022-01-12 |
| 9 | 2021009 | 4502 | Silver | 3 Months | 2022-01-08 | 2022-04-08 |
+------+---------+--------+----------+----------+------------+------------+
TBL_INACTIVEMEMBER:
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| INAMID| int(11) | NO | PRI | NULL | auto_increment |
| GYMID | int(11) | YES | | NULL | |
| END | date | NO | | NULL | |
+-------+---------+------+-----+---------+----------------+
INSERT INTO TBL_INACTIVEMEMBER (Column1, Column2, ColumnN)
SELECT * FROM TBL_ACTIVEMEMBER where END < CURRENT_TIMESTAMP();
This will insert the required values into the table TBL_INACTIVEMEMBER. Change the column names as required.
Now to delete the inactive values from table TBL_ACTIVEMEMBER,
DELETE FROM TBL_ACTIVEMEMBER WHERE END < CURRENT_TIMESTAMP()

Complex INSERT or UPDATE MariaDB tables with data from other MariaDB tables using JOIN or UNION

I need to INSERT or UPDATE data in a table using data from other tables; I understand the basic
insert into table (a,b,c)
select h, i, j
from otherTable
where........
My challenge comes from the fact that the data is spread across multiple tables and in one of the tables the data is metadata stored in rows, not columns. Therefore I need to use JOIN and possible UNION to get what is needed.
Unfortunately after trying everything I read in both the Maria manual, on the Maria forum and on Stack overflow I can not get it to work.
Here is what I am attempting to do:
insert data into dbc_jot_groupmembers in the following fields using source data as shown:
jot_grpid = dbc_bp_groups_members.group_id
jot_bbmemid = dbc_bp_groups_members.user_id
jot_grpmemname = dbc_bp_xprofile_data.value where field_id=3
jot_grpmemnum = dbc_bp_xprofile_data.value where field_id=4
I need the final result to look like this:
select * from dbc_jot_groupmembers;
+--------------+-----------+----------------+---------------+---------------------+-------------+
| jot_grpmemid | jot_grpid | jot_grpmemname | jot_grpmemnum | jot_grpmemts | jot_bbmemid |
+--------------+-----------+----------------+---------------+---------------------+-------------+
| 1 | 17 | hutchdad | +17047047045 | 2021-06-15 14:56:19 | 14 |
| 2 | 24 | hutchdad | +17047047045 | 2021-06-15 19:49:58 | 14 |
| 3 | 25 | hutchdad | +17047047045 | 2021-06-15 19:49:58 | 14 |
| 4 | 17 | hutchmom | +17773274355 | 2021-06-15 19:49:58 | 15 |
| 5 | 24 | hutchmom | +17773274355 | 2021-06-15 19:49:58 | 15 |
| 6 | 16 | ledwards | +14567655645 | 2021-06-15 19:49:58 | 11 |
| 7 | 16 | medwards | +12223334545 | 2021-06-15 19:49:58 | 10 |
| 7 | 20 | medwards | +12223334545 | 2021-06-15 19:49:58 | 10 |
SAMPLE DATA FROM SOURCE TABELS AND TABLE DEFINITIONS:
MariaDB [devDisciplePlaceCom]> describe dbc_bp_groups_members;
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| group_id | bigint(20) | NO | MUL | NULL | |
| user_id | bigint(20) | NO | MUL | NULL | |
| inviter_id | bigint(20) | NO | MUL | NULL | |
| is_admin | tinyint(1) | NO | MUL | 0 | |
| is_mod | tinyint(1) | NO | MUL | 0 | |
| user_title | varchar(100) | NO | | NULL | |
| date_modified | datetime | NO | | NULL | |
| comments | longtext | NO | | NULL | |
| is_confirmed | tinyint(1) | NO | MUL | 0 | |
| is_banned | tinyint(1) | NO | | 0 | |
| invite_sent | tinyint(1) | NO | | 0 | |
+---------------+--------------+------+-----+---------+----------------+
12 rows in set (0.002 sec)
describe dbc_bp_xprofile_data;
+--------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| field_id | bigint(20) unsigned | NO | MUL | NULL | |
| user_id | bigint(20) unsigned | NO | MUL | NULL | |
| value | longtext | NO | | NULL | |
| last_updated | datetime | NO | | NULL | |
+--------------+---------------------+------+-----+---------+----------------+
5 rows in set (0.001 sec)
THIS IS THE LIST OF GROUPS AND WHAT USERS THEY ARE IN.
select group_id,user_id from dbc_bp_groups_members ;
+----------+---------+
| group_id | user_id |
+----------+---------+
| 16 | 13 |
| 16 | 12 |
| 16 | 11 |
| 16 | 10 |
| 17 | 14 |
| 17 | 15 |
| 17 | 16 |
| 17 | 17 |
| 17 | 18 |
| 17 | 19 |
| 20 | 10 |
| 24 | 14 |
| 24 | 16 |
| 24 | 15 |
| 24 | 17 |
| 24 | 19 |
| 25 | 19 |
| 25 | 14 |
| 1 | 14 |
| 11 | 14 |
+----------+---------+
20 rows in set (0.000 sec)
THIS IS THE TABLE CONTAINING THE USERS METADATA. IN MY CASE I NEED THE PHOEN NUMBER AND NAME WHICH ARE IN THE value FIELD WITH A field_id of 3 and 4.
select * from dbc_bp_xprofile_data where user_id > 9 and field_id > 2 AND field_id < 5;
+-----+----------+---------+---------------+---------------------+
| id | field_id | user_id | value | last_updated |
+-----+----------+---------+---------------+---------------------+
| 31 | 3 | 10 | medwards | 2021-06-24 03:11:59 |
| 34 | 3 | 11 | ledwards | 2021-06-24 03:11:24 |
| 37 | 3 | 12 | nedwards | 2021-04-24 14:47:18 |
| 40 | 3 | 13 | iedwards | 2021-04-24 14:47:52 |
| 43 | 3 | 14 | hutchdad | 2021-06-21 14:53:08 |
| 46 | 3 | 15 | hutchmom | 2021-06-24 03:10:58 |
| 49 | 3 | 16 | hutchdaughter | 2021-04-24 16:54:48 |
| 52 | 3 | 17 | hutchson1 | 2021-04-24 16:55:43 |
| 55 | 3 | 18 | hutchson2 | 2021-04-24 16:57:42 |
| 58 | 3 | 19 | hutchson3 | 2021-04-24 16:58:44 |
| 78 | 3 | 25 | demoadmin | 2021-06-08 02:01:39 |
| 158 | 4 | 14 | 7047047045 | 2021-06-21 14:53:08 |
| 190 | 3 | 58 | dupdup | 2021-06-23 19:46:19 |
| 191 | 4 | 15 | 7773274355 | 2021-06-24 03:10:58 |
| 193 | 4 | 11 | 4567655645 | 2021-06-24 03:11:24 |
| 195 | 4 | 10 | 2223334545 | 2021-06-24 03:11:59 |
+-----+----------+---------+---------------+---------------------+
16 rows in set (0.000 sec)
If this can not be done is a single INSERT then I can use an INSERT with subsequent UPDATE statements. I also understand that this is not best practice and violates 3nf and probably several other best practice principles. Unfortunately, I am at the mercy of the application and can not change the code, so the only way to get this to work is to put duplicate data in the database as described below:
It can be done with a single INSERT. However, there are some information need to be addressed as what I've posted in a the comment. In the meantime, here is an example query that you can use to do the operation that you want:
SELECT ROW_NUMBER() OVER (ORDER BY A.group_id, A.user_id) AS 'jot_grpmemid',
A.group_id AS 'jot_grpid',
MAX(CASE WHEN B.field_id=3 THEN B.value ELSE '' END) AS 'jot_grpmemname',
MAX(CASE WHEN B.field_id=4 THEN CONCAT('+',B.value) ELSE '' END) AS 'jot_grpmemnum',
A.user_id AS 'jot_bbmemid'
FROM
dbc_bp_groups_members A JOIN dbc_bp_xprofile_data B
ON A.user_id=B.user_id
GROUP BY A.group_id, A.user_id;
Like I said in the comment, I'm not sure how you get/generate jot_grpmemid because you have two 7 in the expected result so I assume it's a typo. I guess, at this point it's up to you to modify the query accordingly.
Demo fiddle

Mysql - Calculate Times per month - organise result

I'm extracting data from sql by the following SQL Query
SELECT DISTINCT
SEC_TO_TIME(SUM(TIME_TO_SEC(transics_bco.arab))) AS arab,
transics_bco.plate
FROM transics_bco
WHERE transics_bco.extdate BETWEEN '2019-12-01' AND '2019-12-31'
GROUP BY transics_bco.plate
This gives me the following result:
-----------------------
| ARAB | Plate |
-----------------------
| 178:44:43 | 1ABC123 |
| 156:23:44 | 1DEF456 |
-----------------------
Is it possible to get the result shown as this;
---------------------------------------------------------------
| Plate | December 19 | January 20 | February 20 | March 20 |
---------------------------------------------------------------
| 1ABC123 | 178:44:43 | 120:34:56 | ... | ... |
| 1DEF456 | 156:23:44 | 102:34:54 | ... | ... |
| 1GHI789 | 111:22:33 | 156:35:35 | ... | ... |
---------------------------------------------------------------
SQL Sample: transics_bco
----------------------------------------
| id | plate | arab | extdate |
----------------------------------------
| 1 | 1ABC123 | 00:14:23 | 2019-12-01 |
| 2 | 1ABC123 | 00:10:20 | 2019-12-03 |
| 3 | 1ABC123 | 00:45:06 | 2019-12-07 |
| 4 | 1ABC123 | 00:54:45 | 2020-01-02 |
| 5 | 1ABC123 | 00:26:10 | 2020-01-03 |
| 6 | 1ABC123 | 00:43:28 | 2020-01-04 |
----------------------------------------
Would greatly appreciate pointers in the good direction
Adding db describe as requested in the comments;
-
Adding describe of Transics_bco as requested in the comments
===================================================================================================================================================================================================================================================================================================================
| Field | Type | Null | Key | Default | Extra |
===================================================================================================================================================================================================================================================================================================================
| id | int(11) | NO | PRI | null | auto_increment |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| plate | varchar(255) | NO | | null | |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| arab | time | NO | | 00:00:00 | |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| extdate | date | NO | | null | |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT
plate,
december19,
january20,
february20,
march20
FROM
(
SELECT DISTINCT
a.plate,
(
CASE
WHEN
Month(a.extdate) = 12
AND Year(a.extdate) = 2019
THEN
Sec_to_time(Sum(Time_to_sec(a.arab)))
END
)
AS 'December19',
(
CASE
WHEN
Month(a.extdate) = 1
AND Year(a.extdate) = 2020
THEN
a.arab
END
)
AS 'January20, (CASE WHEN MONTH(a.extDate)=2 AND YEAR(a.extDate)=2020 THEN SEC_TO_TIME(SUM(TIME_TO_SEC(a.arab))) END) AS 'february20', (CASE WHEN MONTH(a.extDate)=3 AND YEAR(a.extDate)=2020 THEN SEC_TO_TIME(SUM(TIME_TO_SEC(a.arab))) END) AS 'march20', FROM transics_bco a WHERE transics_bco.extdate BETWEEN '2019-12-01' AND '2019-12-31'
GROUP BY
transics_bco.plate
)
T
GROUP BY
T.plate;

Combine data from three unrelated tables

I need to use a data visualization tool that can only query a single source for a given chart. I have three tables with the data I need to visualize. So, I need to combine them into a single view or output table. Here are the table schemas:
MySQL [bdCaloriesNeeded]> desc activity;
+---------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+----------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | text | YES | | NULL | |
| Gender | text | YES | | NULL | |
| age | int(11) | YES | | NULL | |
| length | text | YES | | NULL | |
| weight | int(11) | YES | | NULL | |
| exercise | int(11) | YES | | NULL | |
| food_consumed | int(11) | YES | | NULL | |
| date | datetime | YES | | NULL | |
+---------------+----------+------+-----+---------+-------+
MySQL [bdCaloriesNeeded]> desc exercise;
+---------------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+---------+------+-----+---------+-------+
| Gender | text | YES | | NULL | |
| Min_Age | int(11) | YES | | NULL | |
| Max_Age | int(11) | YES | | NULL | |
| min_exercise_hours | int(11) | YES | | NULL | |
| med_exercise_hours | int(11) | YES | | NULL | |
| high_exercise_hours | int(11) | YES | | NULL | |
+---------------------+---------+------+-----+---------+-------+
MySQL [bdCaloriesNeeded]> desc food;
+---------------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+---------+------+-----+---------+-------+
| size | text | YES | | NULL | |
| min_pounds | int(11) | YES | | NULL | |
| max_pounds | int(11) | YES | | NULL | |
| min_food_oz_per_day | int(11) | YES | | NULL | |
| max_food_oz_per_day | int(11) | YES | | NULL | |
+---------------------+---------+------+-----+---------+-------+
Here's the actual source data in the above tables:
MySQL [bdCaloriesNeeded]> select * from activity;
+------+----------+--------+------+--------+--------+----------+---------------+---------------------+
| id | name | Gender | age | length | weight | exercise | food_consumed | date |
+------+----------+--------+------+--------+--------+----------+---------------+---------------------+
| 14 | spot | M | 2 | 2'7" | 13 | 5 | 13 | 2017-10-08 00:00:00 |
| 67 | princess | F | 6 | 3'3" | 75 | 3 | 15 | 2017-09-05 00:00:00 |
+------+----------+--------+------+--------+--------+----------+---------------+---------------------+
MySQL [bdCaloriesNeeded]> select * from exercise
+--------+---------+---------+--------------------+--------------------+---------------------+
| Gender | Min_Age | Max_Age | min_exercise_hours | med_exercise_hours | high_exercise_hours |
+--------+---------+---------+--------------------+--------------------+---------------------+
| M | 1 | 2 | 1 | 4 | 6 |
| M | 3 | 7 | 1 | 3 | 4 |
| M | 8 | 15 | 1 | 2 | 2 |
| F | 1 | 2 | 1 | 4 | 6 |
| F | 3 | 7 | 1 | 3 | 5 |
| F | 8 | 15 | 1 | 2 | 2 |
+--------+---------+---------+--------------------+--------------------+---------------------+
MySQL [bdCaloriesNeeded]> select * from food;
+--------+------------+------------+---------------------+---------------------+
| size | min_pounds | max_pounds | min_food_oz_per_day | max_food_oz_per_day |
+--------+------------+------------+---------------------+---------------------+
| small | 1 | 10 | 12 | 18 |
| medium | 11 | 30 | 15 | 30 |
| large | 31 | 100 | 25 | 50 |
+--------+------------+------------+---------------------+---------------------+
Here's the SQL I'm executing:
SELECT activity.id, activity.name, activity.Gender, activity.age, activity.weight, activity.exercise, activity.date, exercise.min_exercise_hours, exercise.high_exercise_hours, food.size, food.min_food_oz_per_day, food.max_food_oz_per_day
from activity, exercise, food
where (
activity.exercise between exercise.min_exercise_hours and exercise.high_exercise_hours
)
and
(
activity.weight between food.min_pounds and food.max_pounds
)
and
(
activity.Gender = exercise.Gender
)
Here's the undesired result I'm getting:
+------+----------+--------+------+--------+----------+---------------------+--------------------+---------------------+--------+---------------------+---------------------+
| id | name | Gender | age | weight | exercise | date | min_exercise_hours | high_exercise_hours | size | min_food_oz_per_day | max_food_oz_per_day |
+------+----------+--------+------+--------+----------+---------------------+--------------------+---------------------+--------+---------------------+---------------------+
| 14 | spot | M | 2 | 13 | 5 | 2017-10-08 00:00:00 | 1 | 6 | medium | 15 | 30 |
| 67 | princess | F | 6 | 75 | 3 | 2017-09-05 00:00:00 | 1 | 6 | large | 25 | 50 |
| 67 | princess | F | 6 | 75 | 3 | 2017-09-05 00:00:00 | 1 | 5 | large | 25 | 50 |
+------+----------+--------+------+--------+----------+---------------------+--------------------+---------------------+--------+---------------------+---------------------+
I'm getting two rows for Princess. I need one row for each dog. The desired result should use Princess's's weight to look up the correct range of food per day, and use her gender and age to look up the correct range of exercise.
I've been banging on this for hours, can't see what doing wrong here.
So interestingly your question says that the tables are Unrelated but they are actually related and this is the whole point of a relational database, to join data based on those relationships.
The issue is that your exercise table is only being joined on exercise hours using the between so princess matches rows 4 and 5 in the exercise table. (the first where clause matches rows 1 and 2 also but the later where clause limits the Gender)
It looks to me like you should also limit the match on the exercise table to age as well as exercise and gender
so add
and (activity.age between exercise.min_age and exercise.max_age)
Also personally i like to use JOIN clauses rather than WHERE - it keeps all the stuff together.
SELECT activity.id,
activity.name,
activity.Gender,
activity.age,
activity.weight,
activity.exercise,
activity.date,
exercise.min_exercise_hours,
exercise.high_exercise_hours,
food.size,
food.min_food_oz_per_day,
food.max_food_oz_per_day
FROM activity
JOIN exercise
ON activity.exercise BETWEEN exercise.min_exercise_hours AND exercise.high_exercise_hours
AND activity.Gender = exercise.Gender
AND activity.age BETWEEN exercise.min_age AND exercise.max_age
JOIN food
ON activity.weight BETWEEN food.min_pounds AND food.max_pounds
Since you are looking for things that may be OUTSIDE of the ranges suggested you may want to consider LEFT JOIN on the exercise and food tables, so that the dogs on the activity table that fall outside of any range will still show up (with NULL values for the missing data for the other table.)
just change the join lines to LEFT JOIN like so:
LEFT JOIN exercise
LEFT JOIN food
See also: What is the difference between "INNER JOIN" and "OUTER JOIN"?

Complex MySQL query summing joined records where parent and child ids are equal

Maybe this will be an easy one for some of you MySQL masters who see this stuff like a level 3 children's book.
I have multiple tables that I'm joining to produce statistical data for a report and I'm getting tripped up at the moment trying to figure it out. It's obviously imperative the figures are correct because it impacts a number of decisions going forward.
Here's the lay of the land (not the full picture, but you'll get the point):
Affiliate Table
+----+-----------+------------+---------------------+
| id | firstname | lastname | created_date |
+----+-----------+------------+---------------------+
| 1 | Mike | Johnson | 2010-11-22 17:44:37 |
| 2 | Trevor | Wilson | 2010-12-23 16:24:24 |
| 3 | Bob | Parker | 2011-11-04 10:33:49 |
+----+-----------+------------+---------------------+
Now our query should only find results for Bob Parker (id 3) so I'll only show example results for Bob.
Affiliate Link Table
+-----+-----------+--------------+-----------+----------+---------------------+
| id | parent_id | affiliate_id | link_type | linkhash | created_date |
+-----+-----------+--------------+-----------+----------+---------------------+
| 21 | NULL | 3 | PRODUCT | fa2e82a7 | 2011-06-15 16:18:37 |
| 27 | NULL | 3 | PRODUCT | 55de2ae7 | 2011-06-23 01:03:00 |
| 28 | NULL | 3 | PRODUCT | 02cae72f | 2011-06-23 01:03:00 |
| 29 | 27 | 3 | PRODUCT | a4dfb2c8 | 2011-06-23 01:03:00 |
| 30 | 28 | 3 | PRODUCT | 72cea1b2 | 2011-06-23 01:03:00 |
| 36 | 21 | 3 | PRODUCT | fa2e82a7 | 2011-06-23 01:07:03 |
| 59 | 21 | 3 | PRODUCT | ec33413f | 2011-11-04 17:49:17 |
| 60 | 27 | 3 | PRODUCT | f701188c | 2011-11-04 17:49:17 |
| 69 | 21 | 3 | PRODUCT | 6dfb89fd | 2011-11-04 17:49:17 |
+-----+-----------+--------------+-----------+----------+---------------------+
Affiliate Stats
+--------+--------------+--------------------+----------+---------------------+
| id | affiliate_id | link_id | order_id | type | created_date |
+--------+--------------+---------+----------+----------+---------------------+
| 86570 | 3 | 21 | NULL | CLICK | 2013-01-01 00:07:31 |
| 86574 | 3 | 21 | NULL | PAGEVIEW | 2013-01-01 00:08:53 |
| 86579 | 3 | 21 | 411 | SALE | 2013-01-01 00:09:52 |
| 86580 | 3 | 36 | NULL | CLICK | 2013-01-01 00:09:55 |
| 86582 | 3 | 36 | NULL | PAGEVIEW | 2013-01-01 00:09:56 |
| 86583 | 3 | 28 | NULL | CLICK | 2013-01-01 00:11:04 |
| 86584 | 3 | 28 | NULL | PAGEVIEW | 2013-01-01 00:11:04 |
| 86586 | 3 | 30 | NULL | CLICK | 2013-01-01 00:30:18 |
| 86587 | 3 | 30 | NULL | PAGEVIEW | 2013-01-01 00:30:20 |
| 86611 | 3 | 69 | NULL | CLICK | 2013-01-01 00:40:19 |
| 86613 | 3 | 69 | NULL | PAGEVIEW | 2013-01-01 00:40:19 |
| 86619 | 3 | 69 | 413 | SALE | 2013-01-01 00:42:12 |
| 86622 | 3 | 60 | NULL | CLICK | 2013-01-01 00:46:00 |
| 86624 | 3 | 60 | NULL | PAGEVIEW | 2013-01-01 00:46:01 |
| 86641 | 3 | 60 | NULL | PAGEVIEW | 2013-01-01 00:55:58 |
| 86642 | 3 | 30 | 415 | SALE | 2013-01-01 00:56:35 |
| 86643 | 3 | 28 | NULL | PAGEVIEW | 2013-01-01 00:56:43 |
| 86644 | 3 | 60 | 417 | SALE | 2013-01-01 00:56:52 |
+--------+--------------+---------+----------+----------+---------------------+
Orders
+------+--------------+---------+---------------------+
| id | affiliate_id | total | created_date |
+------+--------------+---------+---------------------+
| 411 | 3 | 138.62 | 2013-01-01 00:09:50 |
| 413 | 3 | 312.87 | 2013-01-01 00:09:52 |
| 415 | 3 | 242.59 | 2013-01-01 00:09:55 |
| 417 | 3 | 171.18 | 2013-01-01 00:09:55 |
+------+--------------+---------+---------------------+
Now the results that I need should look like this (only show main/parent link id)
+---------+---------+
| link_id | total |
+---------+---------+
| 21 | 451.49 | <- 1 order from parent (21), 1 from child (69)
| 27 | 171.18 | <- 1 order from child (69)
| 28 | 242.59 | <- 1 order from child (30)
+---------+---------+
I'm not quite sure how to write the query so that I can sum where affiliate_link.id and affiliate_link.parent_id are combined. Is this even possible with a couple of JOINs and GROUPing?
I'm not too sure why you have denormalised affiliate_id (by placing it in each table) and, therefore, whether one can rely on all Stats and Orders that stem from a particular Link to have the same affiliate_id as that Link.
If it's possible, I'd suggest changing the AffiliateLink.parent_id column such that parent records point to themselves (rather than NULL):
UPDATE AffiliateLink SET parent_id = id WHERE parent_id IS NULL
Then it's a simple case of joining and grouping:
SELECT AffiliateLink.parent_id AS link_id,
SUM(Orders.total) AS total
FROM AffiliateLink
JOIN AffiliateStats ON AffiliateStats.link_id = AffiliateLink.id
JOIN Orders ON Orders.id = AffiliateStats.order_id
WHERE AffiliateLink.affiliate_id = 3
GROUP BY AffiliateLink.parent_id
See it on sqlfiddle.
If it's not possible to make the change, you can effectively create the resulting AffiliateLink table using UNION (but beware the performance implications, as MySQL will not be able to use indexes on the result):
(
SELECT parent_id, id, affiliate_id FROM AffiliateLink WHERE parent_id IS NOT NULL
UNION ALL
SELECT id , id, affiliate_id FROM AffiliateLink WHERE parent_id IS NULL
) AS AffiliateLink
See it on sqlfiddle.