【问题标题】:Combine data from two different junction tables合并来自两个不同联结表的数据
【发布时间】:2015-05-23 09:30:49
【问题描述】:

我的部分架构如图

我有两个联结表,其中一个将项目映射到类别,第二个将哪些项目映射到特定类别的“特色”。

我现在需要做的是获取特定类别中的所有个项目(不难),但我还需要有一个“特色”列,如果该项目是特色,则会显示对于该类别(如果没有特色,则为 NULL)。

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

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

但我被难住了。

【问题讨论】:

  • 发布您在代码中尝试过的内容
  • 选择 i.*、category.name、category_feat_item.item_id AS 从项目 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 左外连接 category_feat_item ON i.id = category_feat_item.item_id ORDER BY features desc
  • 请在 post..same 查询中编辑它
  • 用示例查询追加编辑
  • 您如何确保特色项目在item_category 表中?特色信息可能应该是item_category 联结表中的标志,而不是单独的表。

标签: mysql sql join


【解决方案1】:

看起来几乎没问题,但您还需要在左外连接中分配 category_id。否则,您将获得该项目的所有特色项目:

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

【讨论】:

  • 我认为你是对的。加入category.id 并将= 1 条件移动到where 子句可能会更好,因此1 文字不会重复两次。
  • 或者至少使用一个参数。
猜你喜欢
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2012-02-18
相关资源
最近更新 更多