Here’s the table that I’m working with:
CREATE TABLE `index` (
`wid` int(7) unsigned NOT NULL,
`pid` int(7) unsigned NOT NULL,
`value` tinyint(3) unsigned NOT NULL DEFAULT '0',
UNIQUE KEY `wid` (`wid`,`pid`),
KEY `pid` (`pid`),
KEY `value` (`value`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
I have integer values of “pid” matching various “wid” that are only unique together.
For instance, I have:
pid - wid - value
1 - 5 - 7
1 - 6 - 5
1 - 7 - 9
2 - 5 - 2
2 - 8 - 4
3 - 8 - 8
3 - 7 - 12
4 - 5 - 5
.. - .. - ..
Now let’s assume I want to get PID where WID matches 5 and 7 order by the highest sum of VALUE.
So PID 1 matches 2 WID’s (5,7) whose sum VALUE is 16 (7 + 9).
And PID 2 matches only 1 WID (5) whose sum VALUE is 2.
And PID 3 matches WID (7) whose sum VALUE is 12.
I need to construct the query that does this and sorts by SUM VALUE descending.
Such as:
SELECT
index.pid, SUM(index.value) TotalSum
FROM index
WHERE
index.wid = 5 or index.wid = 7
GROUP BY UNIQUE(index.pid)
ORDER BY TotalSum DESC
I know this query is incorrect but I’m trying to show what I’m trying to accomplish.
What you are trying to accomplish is approx correct.
Try below :