首页 > 解决方案 > 用于从另一个表中选择 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));
        }

对不起,我希望现在更清楚了。

标签: c#sqlms-access

解决方案


这将为您从产品中获得四列,从基于连接的订单中获得 1 列。

SELECT p.productId, p.category, p.model, p.price, o.quantity
from products p
join orderlines o on p.productid = o.productid

小风格注释——不要使用复数形式的表名。例如,使用产品而不是产品和订单线而不是订单线。没有充分的理由,除了每个人都是这样做的。


推荐阅读