I have a pages
table of URLs and the categories they're associated with. I'm joining it with ITSELF using a constraints
table and using GROUP BY
to get unique URLs, then sorting by highest score.
Problem: The highest score of the group of URLs isn't always selected.
(Background: In production, this will be used to know which pages in the 'from' category should hyperlink to pages in the 'to' category)
I think there is something in this answer, but I can't figure out how to adapt it:
Current Query
SELECT keyword, URL, score FROM
(
SELECT keyword, URL, score
FROM pages
JOIN constraints
ON pages.category = constraints.to
AND constraints.from IN (SELECT category FROM pages WHERE URL = 'https://www.example.net')
ORDER BY score DESC
)
AS x
GROUP BY URL;
pages
+---------+-------------------------+----------+-------+
| keyword | URL | category | score |
+---------+-------------------------+----------+-------+
| Cat | https://www.example.org | 1 | 100 |
+---------+-------------------------+----------+-------+
| Dog | https://www.example.com | 2 | 50 |
+---------+-------------------------+----------+-------+
| Fish | https://www.example.com | 2 | 60 |
+---------+-------------------------+----------+-------+
| Mouse | https://www.example.net | 3 | 1 |
+---------+-------------------------+----------+-------+
constraints
+------+----+
| from | to |
+------+----+
| 1 | 2 |
+------+----+
| 2 | 1 |
+------+----+
| 3 | 2 |
+------+----+
Current output:
+---------+-------------------------+-------+
| keyword | URL | score |
+---------+-------------------------+-------+
| Dog | https://www.example.com | 50 |
+---------+-------------------------+-------+
Dog row selected, despite having a lower score than the Fish row.
Desired output:
+---------+-------------------------+-------+
| keyword | URL | score |
+---------+-------------------------+-------+
| Fish | https://www.example.com | 60 |
+---------+-------------------------+-------+
Edit: Reduced tables to a minimal reproducible example. Added current output. And explained things a little better.