c# - 如何从连接表中检索数据?

标签 c# sql asp.net sql-server

我有 3 个表:

products table
--------------
id
name
...


categories table
----------------
id
name
...


product_categories table
------------------------
product_id
category_id

并通过这个查询加入他们:

select p.*
from products p
join product_categories pc on pc.product_id = p.id
join categories c on pc.category_id = c.id

此查询针对该产品的每个类别返回该产品的多个记录,但我只想获取该产品的一个产品和多个类别。

这是我的输出:

p.Id  p.name --> cat_id cat_name

1 product_1 --> 1 cat1
1 product_1 --> 3 cat3
1 product_1 --> 2 cat2
1 product_1 --> 6 cat6 
2 product_2 --> 5 cat5
2 product_2 --> 1 cat1 
.
.
.

和期望的输出:

p.Id  p.name --> cat_id cat_name,cat_id cat_name,...

1 product_1 --> 1 cat1,3 cat3,2 cat2,6 cat6 
2 product_2 --> 5 cat5,1 cat1 
.
.
.

我该怎么做?

最佳答案

您应该添加 WHERE 子句来指定 ID,并且在 select 子句中您可能想使用 c.* 而不是 p.* 来从类别中获取所有数据。

select p.name, c.*  
from products p
join product_categories pc on pc.product_id = p.id
join categories c on pc.category_id = c.id
where p.id = --smth

关于c# - 如何从连接表中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29644081/

相关文章:

c# - 找不到路径的一部分 'C :\

asp.net - 如何自定义 ASP.NET Web API AuthorizeAttribute 以满足异常需求

c# - 单击动态添加的按钮时如何触发 aspx 脚本?

sql - 使用 SSDT 进行单元测试表

c# - ASP.NET 添加一个 httphandler 来编辑下载的文件名

c# - 实现 IValidatableObject 时 ValidationContext 的目的是什么

c# - 测试复杂实体

c# - ASP.NET WebApi FormsAuthentication 401(未经授权)问题

sql - DB2 Union 导致超时?

mysql - 访问 MySQL 中的最后 N-m 条记录