合并来自两个不同联结表的数据 [英] Combine data from two different junction tables

查看:54
本文介绍了合并来自两个不同联结表的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的架构的一部分如图所示

Part of my schema is as pictured

我有两个联结表,其中一个将项目映射到类别,第二个将特定项目的特征"映射.

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.

我现在要做的是获取特定类别中的 all 个项目(并不困难),但是我还需要有一个特色"列,如果该项目具有特色,则将显示该列对于该类别(如果未显示,则为NULL).

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).

例如,我尝试了LEFT JOIN的各种组合

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

但是我很困惑.

推荐答案

看起来不错,但您还需要在左外部联接中分配category_id.否则,您将获得该商品的所有特色商品:

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

这篇关于合并来自两个不同联结表的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆