如何使用加入来搜索字段?

时间:2019-01-21 11:03:37

标签: c# sql sql-server join

我有以下几列:

Employee Name:

Department:

Designation:

                  Search Button

我想通过连接表来编写搜索查询。 搜索查询会如何?

我只想使用内部联接进行搜索查询。

我尝试了以下操作:

select e.empname, d.depname,designation 
from employee e  
inner join Department d on e.deptid=d.deptid 
inner join Designation de on de.deid=
where empname LIKe '"+Textbox1.text+'%'"' 
   or depname Like '"+ddldept.SelectedValue+"' 
   or designation Like '"+ddldesignation.SelectedValue+"'

如果我错了,请纠正我。

2 个答案:

答案 0 :(得分:2)

我假设您正在使用SQL Server。 和你的表是这样的:

Employee { id, deptid, empname }
Department { id, depname }
Designation { id, empid, designation }

select e.empname, d.depname, de.designation 
from Employee e  
inner join Department d on e.deptid = d.id 
inner join Designation de on e.id = de.empid
where e.empname LIKe '%"+Textbox1.text+"%' 
   or d.depname Like '%"+ddldept.SelectedValue+"%' 
   or de.designation Like '%"+ddldesignation.SelectedValue+"%'

实际上这是一种不好的做法,最好在c#中使用参数化查询:

string sql = "select e.empname, d.depname, de.designation " +
    "from Employee e " +
    "inner join Department d on e.deptid = d.id " +
    "inner join Designation de on e.id = de.empid " +
    "where e.empname LIKe '%@empname%' " +
    "   or d.depname Like '%@deptname%' " +
    "   or de.designation Like '%@designation%'"; 

using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
    command.Parameters.AddWithValue("@empname", Textbox1.text);
    command.Parameters.AddWithValue("@deptname", ddldept.SelectedValue);
    command.Parameters.AddWithValue("@designation", ddldesignation.SelectedValue);
    var results = command.ExecuteReader();
}

答案 1 :(得分:0)

SELECT Employee.id, Employee.NAME, Department.NAME, Designation.Name FROM Employee
INNER JOIN Department
ON Employee.id = Department.employee_id;
INNER JOIN Designation
ON Employee.id = Designation.employee_id;
WHERE Employee.NAME LIKE '%EmployeeInput%';
WHERE Department.NAME LIKE '%DepartmentInput%';
WHERE  Designation.Name LIKE '%DesignationInput%';

也许这会有所帮助。