从不同的表中检索数据

时间:2018-07-04 11:20:54

标签: c# sql .net sql-server

我想从下面的两个表中检索数据。我有一个Products表,其中有P_idP_name列和一个BATCH表,其中p_id_fkProducts表的外键。

这是我的查询;我想从Product表中检索产品名称,因为我已经将Products表的主键作为外键存储在Batch表中。

SqlDataAdapter sda = new SqlDataAdapter("Select batch_id, quantity, left_qty, purchaseDate, manufacturing_date, expiryDate from batch where Convert(DATE, expiryDate, 103) BETWEEN @from AND @to", con);

sda.SelectCommand.Parameters.AddWithValue("@from", Convert.ToDateTime(datePicker1.SelectedDate.Value).ToString("yyyyMMdd"));
sda.SelectCommand.Parameters.AddWithValue("@to", Convert.ToDateTime(datePicker2.SelectedDate.Value).ToString("yyyyMMdd"));

3 个答案:

答案 0 :(得分:2)

如果要从两个表中检索数据,则需要使用SQL JOIN

我不确定您的桌子的确切组成,但如下所示

Select batch_id,
product_name,
quantity,
left_qty,
purchaseDate,
manufacturing_date,
expiryDate
from batch B
INNER JOIN Products P
ON P.P_id = B.P_id
where Convert(DATE,expiryDate,103) BETWEEN @from AND @to

答案 1 :(得分:1)

您需要在此处进行联接或交叉申请。

选项1-内部联接:

    Select         
    b.batch_id,pd.product_name,quantity,left_qty,
    purchaseDate,manufacturing_date,expiryDate from batch b 
    inner join product pd on pd.p_id = b.p_id  where Convert(DATE,expiryDate,103) 
    BETWEEN @from AND @to

选项2交叉应用:

    Select         
    b.batch_id,pd.product_name,quantity,left_qty,
    purchaseDate,manufacturing_date,expiryDate from batch b 
    cross apply
    (
     select product_name from product p
     where p.p_id = b.p_id
    ) pd
    where Convert(DATE,expiryDate,103) 
    BETWEEN @from AND @to

有关交叉应用的更多信息,请参见here

答案 2 :(得分:1)

不确定我是否正确理解了您的问题,但是我相信对于您的查询,您正在寻找一些简单的东西,例如ProductsBatch表之间的JOIN:

SELECT
    P.P_id,
    P.P_name,
    B.batch_id,
    B.product_name,
    B.quantity,
    B.left_qty,
    B.purchaseDate,
    B.manufacturing_date,
    B.expiryDate
FROM Batch AS B
INNER JOIN Products AS P
ON B.p_id_fk = P.P_id
WHERE CONVERT(DATE, B.expiryDate, 103) BETWEEN @from AND @to
您提供的

p_id_fk名称可能不是Batch表中的实际列名称,而是外命名约束本身的名称,如命名约定所示(后缀_fk