0

I am trying to sum values from a tables column where some conditions are met but I can't figure out the returned values from mysql.

I have run the below script.

create table robot_data(name varchar(20), value float, x int, y int, z int);


insert into robot_data(name, value, x, y, z) values("temperature", 27.99, 1, 88, 0);
insert into robot_data(name, value, x, y, z) values("temperature", 27.99, 1, 88, 0);
insert into robot_data(name, value, x, y, z) values("temperature", 27.99, 1, 88, 0);
insert into robot_data(name, value, x, y, z) values("temperature", 27.99, 1, 88, 0);

insert into robot_data(name, value, x, y, z) values("humidity", 7.99, 1, 88, 0);
insert into robot_data(name, value, x, y, z) values("humidity", 7.99, 1, 88, 0);
insert into robot_data(name, value, x, y, z) values("humidity", 7.99, 1, 88, 0);
insert into robot_data(name, value, x, y, z) values("humidity", 7.99, 1, 88, 0);
insert into robot_data(name, value, x, y, z) values("humidity", 7.99, 1, 88, 0);
insert into robot_data(name, value, x, y, z) values("humidity", 7.99, 1, 88, 0);




SELECT  COUNT(temp.value) FROM 

(SELECT value, name from robot_data where name ='temperature') as temp,
(SELECT value, name from robot_data where name ='humidity') as hum;

SELECT COUNT(value) FROM robot_data;

I expect the first and second select to return the same results but they don't. The first one returns 24 and the second one 10 which is correct.

In reality what I want to do is this in the first select:

SELECT ROUND(SUM(temp.value + hum.value))...

But I want none matching rows to return null since the values for temperature are 4 and humidity 6. I will appreciate if I can get an insight on what is happening.

2
  • What is your expected result? Commented Mar 24, 2019 at 10:21
  • I have two expectations the first one is in the question but the answer below has clarified that it is essentially a table join this I did not know. The second one is to sum matching rows in temperature and humidity and null for rows without matching values so I will have 6 rows with the first four summing temp and humidity and the last one null. Commented Mar 24, 2019 at 15:54

1 Answer 1

2

The second return 10 because you have insert 10 rows in table robot_data

The first return 24 because your syntax

FROM ( ) temp, ( ) hum 

produces a cross join between the table returned by subquery from temperature of 4 rows and table return from subquery for humidity of 6 rows. So 6x4 = 24 rows.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok. This was insightful and I managed to solve my problem by using left joins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.