MYSQL How to preserve order of second table in a join operation?

Roman Kubiv :

I am trying to make a search system for listings in my database.

The user can enter a search query, which will then be split up by word by word. The words are then matched to their tag IDs in my database (a tag is just one word). Then the link table for tags and listing items is searched for listingItemIDs and ListingIDs that contain those tags. The results are then sorted by the amount of tags that a listing contains (listings that contain more tags are shown first). Finally the listing data is selected.

My issue is that when i join the ordered listing ID results with the listings table, the order of the listings is wiped.

I tried reversing the order of the two tables in the join statement but i kept getting SQL errors.

SELECT * FROM listing
JOIN 
   (SELECT listingID
    FROM listing_item_tags
    JOIN (
        SELECT tagID FROM tags WHERE tagName IN ("2","1","4")
    ) as tagIds
    ON listing_item_tags.tagID = tagIds.tagID
    GROUP BY listingID
    ORDER BY COUNT(listingID) DESC
    ) AS ListingIDS
ON listing.listingID = ListingIDS.listingID
Strawberry :

Something like this should suffice...

SELECT l.* 
  FROM listing l
  JOIN 
     ( SELECT listingID
            , COUNT(*) total
         FROM listing_item_tags lt
         JOIN tags t
           ON t.tagID = lt.tagID
        WHERE t.tagName IN (2,1,4)
        GROUP 
           BY listingID
      ) x
     ON ...
  ORDER  
     BY total DESC

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=170131&siteId=1