How can I modify the following query to restrict the addition from choice to only one row per nid, the one with the highest value in the field foo? That is, there are multiple rows in the choice table with the same nid, and I want the highest foo of each nid to be joined to node.
SELECT *
FROM `node`
LEFT JOIN `choice` ON node.nid = choice.nid
Try it out on SQLFiddle.
EDIT:
Speaking bout adding
barinto the list.In the subquery I’m finding
MAX(foo)for eachnid, thereforeGROUP BY nid. There’s no logic in addingbaras it is, you should either use an aggregate on that column or include it into theGROUP BY. It is MySQL “extension” (which I personally find error prone), that allows you to make such things. I assume, that MySQL doesMAX(bar)behind the scenes.If you’ll run query:
you’ll see, that
MAX(foo)andMAX(bar)are taken from different rows.Compare the output with the following:
As soon as
nid+foocombination is unique withinchoiceI would recommend not to add more values into the subquery. Otherwise the overall approach needs to be changed.