【问题标题】:How To implement inner join on self dependent table如何在自依赖表上实现内连接
【发布时间】:2014-11-02 10:48:00
【问题描述】:

Categories

1 | Pen       | 3
2 | Book      | 3
3 | Education | null
4 | Shirt     | null

Product

1 |  10.00 | Parker-Pen   | the description | 1000  | 1
2 |  35.00 | Dairy        | the description | 500   | 2
3 |  9.00  | Dux-Pen      | the description | 1000  | 1
4 | 350.00 | GeographyMap | the description | 30    | 3
4 | 250.00 | PoloShirt    | the description | 100   | 4

这些是我实际检索类别 id 为 3 的产品的表格。

这是我用来检索数据的查询

select p.name, c.name 
from product p 
    inner join Categories c on p.Categories_id=c.id 
    inner join Categories c2 on c2.id=3 or c2.parent=3

它实际上是在多次检索数据。还有马球衫,它不在类别 ID 上。

你能解释一下有什么问题吗?对产品进行分类的更好方法是什么

【问题讨论】:

  • 你能定义数据列的实际含义吗?还有你的预期输出是什么,因为很难理解你想要实现什么。
  • 你的预期输出是什么
  • @Ganesh_Devlekar 我想获取类别 id 为 3 的产品以及类别 id 的父 id 为 3 的产品
  • @dotnetom 我想获取类别 id 为 3 的产品以及类别 id 的父 id 为 3 的产品

标签: sql-server database join self-join


【解决方案1】:

如果只允许一个层次结构,你应该得到这样的查询的答案:

select p.name, c.name 
from product p 
    inner join Categories c on p.Categories_id=c.id 
where c.id=3 or c.parent=3

【讨论】:

  • 您不需要第二次加入,因为您没有检查第二张表上的任何条件
  • 我怎样才能用这个表获得多层次的层次结构,我必须改变表还是可以通过sql命令获得它?
  • 您可以通过例如将Educarion 的父级设置为4 来添加第二级层次结构,但在这种情况下,我编写的查询将不起作用
  • 是的,我知道这张桌子可以做到,但我只想知道命令是什么
猜你喜欢
  • 2020-10-10
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多