Assuming that the url parsing is correct and the data is actually set up correctly in the DB I think your SQL query is wrong. My suggestion is that you replace it by calling wp_query()
api with the relevant parameters.
Another suggestion that might not be a bug is not to use guid, as it is not a reliable source for a post address. It is better to get the post ID and use get_permalink()
to get its url