I program a site and I can't get this query right.
I have a table that contain the channels
select * from `channels`
and I have another table that contain the statistics of viewing every page in the site.
To get the all visits to a specific channel I will write
SELECT SUM(ip) AS visits FROM `log` where `module` = 'channels' and mid = '15'
where 15 is equal the id of a row in the channels
table.
The query that I need to write should use a join with sum to select * from channels
and add an extra cell (value) to get the number of visits for every id in Channels.
From comments to answers:
The table called Channels contains columns id and name. The table called Log contains columns ip, module, mid. The
log.module = 'channel'
;log.mid = channel.id
. Every channel id (such as '15') can get all of its visits by the querySELECT SUM(ip) AS visits FROM log where module = 'channels' and mid = '15'
.
Roughly:
CREATE TABLE Channels (ID INTEGER, Name CHAR(30), PRIMARY KEY ID);
CREATE TABLE Log (IP CHAR(16), Module CHAR(10), MID INTEGER REFERENCES Channels(ID));
You need to provide some more information on the tables to get a good answer. Specifically, you've not explicitly provided information about which column(s) in Channels join with which columns in Visits. However, with some reading between the lines, a JOIN query with GROUP BY should do the job:
SELECT c.id, COUNT(*) AS Visits
FROM Channels AS C
JOIN Log AS L ON c.id = l.mid
WHERE l.module = 'channels'
GROUP BY c.id;
You can also move the WHERE clause into the ON condition, but the optimizer should do that automatically for you.
If you want to see all Channel records, even those with zero counts, you have to use a LEFT OUTER JOIN (abbreviated LEFT JOIN) and COUNT(x) where x
is an appropriate column in the Log table:
SELECT c.id, COUNT(l.mid) AS Visits
FROM Channels AS C
LEFT JOIN Log AS L ON c.id = l.mid
WHERE l.module = 'channels'
GROUP BY c.id;