【问题标题】:How To Get SIngle Row Value from multiple duplicate value in SQL Database by using MVC4如何使用 MVC4 从 SQL 数据库中的多个重复值中获取单行值
【发布时间】:2016-03-03 23:23:04
【问题描述】:

我有三张桌子

1-Category 有两个字段: (i)Id (ii)姓名

2-具有 4 个字段的产品: (i)Id (ii)P_Name (iii)Category_Id (iv)描述

3-ImagePath 有 3 个字段: (i)Id (ii)Product_Id (iii)Imagepath

这三个表具有外键关系,例如类别表的 ID 存储在产品表中,产品表 ID 存储在 Imagepath 表中。 在 Product_Id 的基础上,ImagePath 表中存储了多个图像,如下图所示:

现在我想根据 Product_Id 获取单个图像 请帮我解决这个问题 提前谢谢你。

【问题讨论】:

  • 您是否正在编写用于从数据库中获取数据的 SQL 查询?在这种情况下,您可能需要在 SQL 查询中使用“Group BY”和“First()”函数

标签: asp.net sql-server asp.net-mvc-4


【解决方案1】:
  select * from (select Products.id,Imagepath,(ROW_NUMBER() over ( order by Products .id )) as rowno   from Category ,Products , ImagePath  where  ImagePath.Product_Id  = Products.id and  Products.Category_Id =Category.id   ) t where rowno=1

你可以通过改变rowno的值来改变输出

【讨论】:

  • 你能解释一下 Products.Id 和 Imagepath 响应表中的哪些字段的第一个选择语句
  • Products.Id是product表中的主键,由于id在3张表中使用,为了避免歧义,所以使用。 imagepath 是 imagepath 表中的一个字段
  • 在你的代码之前,我写了这行代码来显示基于 Category_Id 的值。现在我想从 ImagePath Table 中获取基于 Cat_Id 的单个数据
  • 我编写了一个存储过程来根据我想从 ImagePath 表中存在的 Multiple 值中获取的 CategoryID 获取值 alter proc sp_getImgByCat @catid int as begin select p.Id,p.Cat_Id,p.P_Name,img.ImagePath from P_Product p INNER JOIN P_ImagePath img ON p.Id=img.P_Id where p.Cat_Id=@catid end
猜你喜欢
  • 2016-07-06
  • 1970-01-01
  • 2019-03-17
  • 2013-04-30
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
相关资源
最近更新 更多