过滤详细信息表结构查询语言

时间:2015-02-01 13:23:20

标签: c# sql-server

查询明细表

Main Table
1 .PK

Detail Table
1. PK
2. Detail description.

如果mysql我可以将主表PK分组为重复问题但是如何在sql server中实现?因为sql server需要类似聚合的东西

E.g

(vehicle) Main Table 

Car 
bikes
van

(vehicleItem) Detail Table

Car->item a,item b
bikes-> item a,item c.. 
van->item b ,item c

我想过滤一个查询,比如我想过滤一个项目?看起来效率很低,无法在子循环中调用。即使把它放在一列中的所有细节项都认为不正确但是当搜索项目id(数字)可能时是相同的数字,除非项目ID是guid和明显不同。 **主要目的是输出列表而不是交叉链接:) ya ..分组很酷,如果你想总结一下。

var sql = "select * from vehicle ";

var command = new SqlCommand(connection,sql);
try {
 var reader = command.ExecuteReader();
 if (reader.HasRows) {
 while (reader.Read())
  if (!string.IsNullOrEmpty(Request.QueryString["ItemIdValue[]"])){
   var d = Request.QueryString.GetValues("ItemIdValue[]");
    if (d != null){
     if (d[0].Contains("all")){
      if (GetItemExist("  AND vehicleItem.itemId  in (SELECT itemId from item ) ")){ }
      }else{
    if (GetItemExist(" AND vehicleItem.itemId IN ( " + itemFilter.Remove(itemFilter.Length - 1) + " ) ")){ }
      }
     }
    }
   }
 }
}


At last thinking back, why not select main table and in subquery..
var sql = "select * from vehicle ";
if (!string.IsNullOrEmpty(Request.QueryString["itemIdValue[]"])){
 var d = Request.QueryString.GetValues("itemIdValue[]");
  if (d != null){
   if (d[0].Contains("all")){
    sql = sql + @" 
    AND vehicleId IN (
     SELECT  vehicleId 
     FROM    vehicle
     JOIN    vehicleItem
     ON      vehicle.vehicleId     =   vehicleItem.vehicleId 
     WHERE   vehicleItem.itemId in 
     (SELECT itemId from item)    
                    ) ";
} else{
 for (var e = 0; e < d.Length; e++){
  itemFilter += d[e] + ",";
  _fieldVariable.Add("itemIdValue[]");
  _valueVariable.Add(d[e]);
 }
 sql = sql + @" 
 AND vehicleId IN (
  SELECT  vehicleId 
  FROM    vehicle
  JOIN    vehicleItem
  ON      vehicle.vehicleId     =   vehicleItem.vehicleId 
  WHERE   vehicleItem.itemId in ( " + itemFilter.Remove(itemFilter.Length - 1) + " )   ) ";
 }
}
        }

1 个答案:

答案 0 :(得分:0)

当连接两个表t1和t2时,创建包含来自表t1和表t2的所有匹配行的结果集。如果您只想在每个t1行中生成一行,那么您可以相应地过滤联接。

有几种方法可以做到这一点:

  • 调整联接的ON子句
  • 相应地分组
  • 指定WHERE子句

如果您想在请求中使用分组,可以使用如下查询:

SELECT m.PK, min(d.Detail) 
FROM Main m 
LEFT JOIN Detail d on d.PK=m.pk 
WHERE d.Detail = 'item a'
GROUP by m.PK

这样,每个PK都会获得一行,并且具有最小值。您也可以使用其他聚合函数。请参阅https://msdn.microsoft.com/en-us/library/ms173454.aspx

修改:添加WHERE子句以过滤&#34;项目a&#34;。