c# - 用于从另一个表中选择 1 个表和 1 个列(与表 1 中的名称相同)中的所有内容的 SQL 查询
问题描述
我有 3 张桌子。表格1 :
Products:
ProductId Category Model Price Quantity
表2:
OrderLines:
OrderId ProductId Quantity
表3:
Orders:
OrderId CustomerId
(还有一个客户表,但没关系)
现在我想从 Products 表中选择 OrderLines 表中 ProductId = ProductId 的所有产品数据,但从 OrderLines 表中获取(相同产品的)数量数据。
尝试了各种查询,找不到一个有效的。
这是我尝试的最后一件事:
SELECT tb1.* ,tb2.[Quantity]
FROM [Products] tb1, [OrderLines] tb2
WHERE tb1.[ProductId] IN (
SELECT [ProductId] FROM [OrderLines] WHERE OrderId = @orderId)
INNER JOIN [OrderLines] tb2 ON[Products].Quantity = [OrderLines].Quantity";
没用。
有什么建议么?
非常感谢。
示例数据:订单:OrderId CustomerId
1 2
OrderLines:
OrderId ProductId 数量
1 3 1
1 4 5
产品:
ProductId 类别 型号 价格 数量
3 "wow" "hd" 30 5
4 "yay" "sd" 50 60
5 "wow" "ss" 12 5
预期输出:产品数组:每个对象都是产品类型,具有与表中相同的字段。(已经定义了它的类)。数组中的第一个对象是:
productId = 3, Category="wow",Model="hd", price=30,Quantity = 1 (**1! not 5)
第二个对象:
productId = 4, Category="yay" ,型号=”sd”,价格=50,数量=5
我在 Visual Studio、Winforms 中使用 c#。数据库是Access。这是功能:
public Product[] GetProductsByOrderId(int orderId)
{
DataSet ds = new DataSet();
ArrayList arrProducts = new ArrayList();
//"SELECT tb1.* ,tb2.[Quantity] FROM [Products] tb1, [OrderLines] tb2 WHERE tb1.[ProductId] IN (SELECT [ProductId] FROM [OrderLines] WHERE OrderId = @orderId) INNER JOIN [OrderLines] tb2 ON[Products].Quantity = [OrderLines].Quantity"
string cmdStr = "SELECT p.*, ol.Quantity as OrderLineQuantity from Products as p inner join OrderLines as ol on p.Id = ol.ProductId";
using (OleDbCommand command = new OleDbCommand(cmdStr))
{
command.Parameters.AddWithValue("@orderId", orderId);
ds = GetMultipleQuery(command);
}
DataTable dt = new DataTable();
try
{
dt = ds.Tables[0];
}
catch { }
foreach (DataRow tType in dt.Rows)
{
Product productData = new Product();
productData.ProductId = int.Parse(tType[0].ToString());
productData.Category = tType[1].ToString();
productData.Model = tType[2].ToString();
productData.Price = double.Parse(tType[3].ToString());
productData.Quantity = int.Parse(tType[4].ToString());
arrProducts.Add(productData);
}
return (Product[])arrProducts.ToArray(typeof(Product));
}
对不起,我希望现在更清楚了。
解决方案
这将为您从产品中获得四列,从基于连接的订单中获得 1 列。
SELECT p.productId, p.category, p.model, p.price, o.quantity
from products p
join orderlines o on p.productid = o.productid
小风格注释——不要使用复数形式的表名。例如,使用产品而不是产品和订单线而不是订单线。没有充分的理由,除了每个人都是这样做的。
推荐阅读
- symfony - 脚本启动时的 Symfony 5 教义迁移错误
- sql - 比较两个表并使用 SQL Server 过程在第三个表中插入所有具有添加或删除状态的记录
- three.js - 3d-force-graph 和 Three.js - 为单个节点和节点组添加几何发光/大气材质/简单纹理
- ios - 核心数据错误:在范围内没有 NSManagedObjectContext 时无法获取
- excel - 在vba中使用带有多个条件的if语句循环遍历给定范围内的每一行
- json - 如何使用 Azure ARM 模板从 keyvault 传递秘密值
- spring-security - Spring hybris 中基于路径的漏洞
- docker - 来自多级 Dockerfiles 的 `npm build` 和 `COPY --from` 失败并显示 `COPY failed: stat /mnt/data/docker/overlay2/xxxxx/merged/app/build
- c# - 在 ASP.NET MVC 和 Azure 中注册后发送电子邮件确认延迟
- variables - 使用变量创建文件夹时如何修复括号扩展