如何查询多个表 [英] How to query with multiple tables

查看:92
本文介绍了如何查询多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目包含2个表格。

DetailsTB和ImageTB



现在DetailsTB包含主键作为两列收据的复合键,Passenger_Name

例如PRIMARY KEY(收据,Passenger_Name)



和这个FOREIGN KEY(收据,Passenger_Name)是ImageTB的主键



例如FOREIGN KEY(Receipt,Passenger_Name)REFERENCES DetailsTB(Receipt,Passenger_Name),PRIMARY KEY(Receipt,Passenger_Name)表ImageTB



我想在两个表中选择记录但是我的查询无法正常工作



我的查询:



cmd =新的SqlCommand(SELECT Picture FROM ImageTB WHERE DetailsTB.Passenger_Name ='+ datagridview_details.Rows [e.RowIndex] .Cells [6] .Value.ToString()+'AND DetailsTB.Passenger_Name = ImageTB.Passenger_Name,con);



它给了我各种sqlexception错误。



所以plz帮我查询同样的问题。



提前感谢

My Project contain 2 tables.
DetailsTB and ImageTB

Now DetailsTB contain Primary key as a Composite Key of two column of Receipt,Passenger_Name
e.g. PRIMARY KEY(Receipt, Passenger_Name)

and this FOREIGN KEY(Receipt, Passenger_Name) is Primary key for ImageTB

e.g. FOREIGN KEY (Receipt, Passenger_Name) REFERENCES DetailsTB(Receipt, Passenger_Name), PRIMARY KEY (Receipt, Passenger_Name) for table ImageTB

I want to select record in both table but my query cant work properly

My query:

cmd = new SqlCommand("SELECT Picture FROM ImageTB WHERE DetailsTB.Passenger_Name = '" + datagridview_details.Rows[e.RowIndex].Cells[6].Value.ToString() + "' AND DetailsTB.Passenger_Name = ImageTB.Passenger_Name", con);

it gives me various sqlexception error.

So plz help me for the same query.

thanks in advance

推荐答案

在查询中使用JOIN

use JOIN in your query
cmd = new SqlCommand(string.Format("SELECT Picture FROM ImageTB itb join DetailsTB dtb on dtb.Passenger_Name = itb.Passenger_Name WHERE dtb.Passenger_Name = '{0}'", datagridview_details.Rows[e.RowIndex].Cells[6].Value.ToString()), connection);





你还需要检查atagridview_details.Rows [e.RowIndex] .Cells [6] .Value不为空

(或者你会得到NullReferenceException)



并且还要注意Sql注入



also you need check that atagridview_details.Rows[e.RowIndex].Cells[6].Value is not null
(or you will get NullReferenceException)

and also be aware of Sql injection


我建​​议你看一下JOIN的使用。



基本例子: http://www.w3schools.com/sql/sql_join.asp [ ^ ]
I suggest you look at the use of JOINs.

Basic example: http://www.w3schools.com/sql/sql_join.asp[^]


你必须了解SQL Join才能使用多个表条件。



访问此处了解...



SQL检索数据a来自多个表格 [ ^ ]







使用多个表格加入 [ ^ ]
you have to understand about SQL Join to use multiple tables condition.

visit here to understand ...

SQL Retrieve data from multiple tables[^]

or

Use Join With Multiple Tables[^]


这篇关于如何查询多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆