Skip to content
Advertisement

Is there a better way to simplify many nested select statements?

I am worried that I think about SQL wrongly. I am able to hack queries together to do what I want, but they end up quite ludicrous with multiple nested selects. Here is an example that I can’t fathom how to simplify (let alone how to improve the performance). One of my main issues was how to pick the most recent message out of the union when I group the users together. Wrapping it in another select just to order it works, but seems too ugly and I am worried about performance with doing that all the time. My plain english explanation of what the query does is:

Looks at sent and received messages relevant for a given user (in this case hard-coded to user id 1), and returns a distinct list of all users that have messaged me along with when the most recent message was either sent or received between us.

The uid field that I am storing in another meta table unfortuantely has to be returned too, making the whole thing even more complex:

Fiddle

db fiddle here: https://www.db-fiddle.com/f/6z7jVN6DtUYcuZwSXxeMX7/0

Sample data:

Advertisement

Answer

Another possible and simpler way would be

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement