I have the following talbes:
CREATE TABLE topics (
id INT,
text VARCHAR(100),
parent VARCHAR(1)
);
CREATE TABLE sentiment (
id INT,
grade INT,
parent VARCHAR(1)
);
And the following data:
INSERT INTO topics (id, text, parent) VALUES (1, 'Cryptocurrency', 'A');
INSERT INTO topics (id, text, parent) VALUES (2, 'Cryptocurrency', 'B');
INSERT INTO topics (id, text, parent) VALUES (2, 'ETH', 'B');
INSERT INTO sentiment (id, grade, parent) VALUES (2, 0 , 'A');
INSERT INTO sentiment (id, grade, parent) VALUES (2, 1 , 'A');
INSERT INTO sentiment (id, grade, parent) VALUES (2, 1 , 'A');
INSERT INTO sentiment (id, grade, parent) VALUES (2, 1 , 'A');
INSERT INTO sentiment (id, grade, parent) VALUES (2, 0 , 'B');
INSERT INTO sentiment (id, grade, parent) VALUES (2, 1 , 'B');
I want to select count of each topics.text
and shared parent sum of sentiment.grade
.
So I came up with the following query:
SELECT
count(topics.text),
topics.text,
sum(sentiment.grade)
FROM topics
inner join sentiment on (sentiment.parent = topics.parent)
group by text
The result:
| count(topics.text) | sum(sentiment.grade) | text |
| ------------------ | -------------------- | -------------- |
| 6 | 4 | Cryptocurrency |
| 2 | 1 | ETH |
---
I only have a problem with the first column, the real count of Cryptocurrency
is 2 and the real count of ETH
is 1.
Can you fix this query?
(I’m using mysql8, would be glad to have 5.7 compliant if possible)
2
Answers
As you have two rows with
text=cryptocurrency
intopics
, one withparent=A
and the other withparent=B
, when you join you should expect to see 6 rows forcrpytocurrency
(the first row oftopics
matches the first four ofsentiment
, and the second row oftopics
matches the last two ofsentiment
). You can see that if you change your original query to this one:I guess you want to see the number of
topics
with the sametext
and the totalgrades
their parents have (forcryptocurrency
, the sum ofA
andB
). This could help you: