1

Part of my schema is as picturedCategory, Items

I have two junction tables, one of which maps Items to Categories and the second which maps what items are "featured" for a particular category.

What I need to do now is get all items that are in a particular category (not difficult), but I also need to have a column "featured" that would display if the item is featured for that category (NULL if not featured).

I've tried various combinations of LEFT JOIN for example

SELECT i.*, category.name, category_feat_item.item_id AS featured
FROM item AS i
INNER JOIN item_category ON i.id = item_category.item_id
INNER JOIN category ON category.id = item_category.category_id AND category.id =1
LEFT OUTER JOIN category_feat_item ON i.id = category_feat_item.item_id
ORDER BY featured DESC

but I'm stumped.

6
  • post what you have tried in codes as well
    – Tharif
    May 23, 2015 at 9:31
  • select i.*, category.name, category_feat_item.item_id AS featured from item AS i INNER JOIN item_category ON i.id = item_category.item_id INNER JOIN category ON category.id = item_category.category_id AND category.id =1 LEFT OUTER JOIN category_feat_item ON i.id = category_feat_item.item_id ORDER BY featured desc
    – jimmy
    May 23, 2015 at 9:39
  • kindly edit that in post..same query
    – Tharif
    May 23, 2015 at 9:49
  • Edited with sample query append
    – jimmy
    May 23, 2015 at 9:55
  • 1
    How do you ensure that featured items are in the item_category table? The featured information should probably be a flag in the item_category junction table, rather than a separate table. May 23, 2015 at 11:26

1 Answer 1

1

Looks almost ok but you need to assign the category_id in the left outer join as well. Otherwise you get all featured items of the item:

SELECT i.*, category.name, category_feat_item.item_id AS featured
FROM item AS i
INNER JOIN item_category ON i.id = item_category.item_id
INNER JOIN category ON category.id = item_category.category_id AND category.id =1
LEFT OUTER JOIN category_feat_item ON i.id = category_feat_item.item_id AND category_feat_item.category_id = 1
ORDER BY featured DESC
2
  • I think you're right. Might be even better to join on category.id and move the = 1 condition to a where clause, so the 1 literal is not repeated twice.
    – Andomar
    May 23, 2015 at 10:39
  • Or at least use a parameter.
    – sfrutig
    May 23, 2015 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.