嵌套选择三个表

时间:2013-08-25 03:58:11

标签: c# sql

嗨我有三张这样的桌子

////////////////////////////////////////////
PlaceCodename   |     DeviceConfig   |   DevInOut
----------      |     ------------   |   --------
Place_name      |     IP   (PK)      |   IP
Place_code (PK) |     Place_code     |   Action
                |     TypeofUseCode  |   Cardserial (PK)
                |     deevNum        |   date   (PK)
                                     |   time    (PK)

对于每个Cardserial,都有一些可以重复的IP。这意味着DevInOut中的主键是(日期,时间和Cardserial)的组合。

我想给Cardserial并基于IP,从DeviceConfig获取Place_code,并根据它从PlaceCodename表获取Place_name。

我写了这个查询,但它不起作用:

SqlDataAdapter a = new SqlDataAdapter("select Place_code from DeviceConfig inner join        (select IP from DevInOut where Cardserial = '" + textBox12.Text + "') tb on
DeviceConfig.IP = tb.IP)", con);
SqlCommandBuilder comdBuilder = new SqlCommandBuilder(a);
DataTable t = new DataTable();
t.Locale = System.Globalization.CultureInfo.InvariantCulture;
a.Fill(t);
bindingSource1.DataSource = t; 
........

我甚至尝试过数据表它也没用。我怎么能解决我的问题?

2 个答案:

答案 0 :(得分:1)

您说您想要Place_name,但您的代码显示您选择了Place_code。您只需要一个正常的WHERE即可解决此问题:

SqlDataAdapter a = new SqlDataAdapter(string.Format("SELECT Place_name FROM PlaceCodeName, DeviceConfig, DevInOut WHERE Cardserial = '{0}' AND PlaceCodeName.Place_code = DeviceConfig.Place_code AND DeviceConfig.IP = DevInOut.IP",textBox12.Text), con);

答案 1 :(得分:0)

Select Place_Name 
From PlaceCodename  N 
     INNER JOIN DeviceConfig   D 
                 on N.Place_code = D.Place_code     
     INNER JOIN DevInOut IO 
                 ON D.IP = IO.IP 
WHere IO.Cardserial ='YOUSERIAL'