使用join with where子句

时间:2014-04-09 07:38:32

标签: sql sql-server

SELECT * FROM Base b 
JOIN Departement d ON b.d_id = d.d_id 
JOIN Block bl ON b.b_id = bl.b_id 
JOIN Model m ON b.m_id = m.m_id 
WHERE (b.s_no LIKE '%' + @search +'%' 
OR b.ser_no LIKE '%' + @search + '%'
OR b.user_name LIKE '%' + @search + '%' 
OR d.d_id LIKE '%' + @search + '%' 
OR bl.b_id LIKE '%' + @search + '%' 
OR m.m_id LIKE '%' + @search + '%' 
OR d.d_name LIKE '%' + @search + '%' 
OR m.m_name LIKE '%' + @search + '%') ";

我尝试编写一个sql命令来搜索数据库。但它不起作用。这是假的用法吗?

1 个答案:

答案 0 :(得分:0)

也许你需要外连接而不是内连接.. 不确定你的情况有什么问题,但尝试使用左连接。 可能你只是在一个表中有数据,但在另一个表中没有相应的数据..

而不是

 SELECT * FROM Base b 
 JOIN Departement d ON b.d_id = d.d_id 
 JOIN Block bl ON b.b_id = bl.b_id 
 JOIN Model m ON b.m_id = m.m_id 
 WHERE (b.s_no LIKE '%' + @search +'%' 
 OR b.ser_no LIKE '%' + @search + '%'
 OR b.user_name LIKE '%' + @search + '%' 
 OR d.d_id LIKE '%' + @search + '%' 
 OR bl.b_id LIKE '%' + @search + '%' 
 OR m.m_id LIKE '%' + @search + '%' 
 OR d.d_name LIKE '%' + @search + '%' 
 OR m.m_name LIKE '%' + @search + '%') ";

试试这个:

 SELECT * FROM Base b 
 LEFT JOIN Departement d ON b.d_id = d.d_id 
 LEFT JOIN Block bl ON b.b_id = bl.b_id 
 LEFT JOIN Model m ON b.m_id = m.m_id 
 WHERE (b.s_no LIKE '%' + @search +'%' 
 OR b.ser_no LIKE '%' + @search + '%'
 OR b.user_name LIKE '%' + @search + '%' 
 OR d.d_id LIKE '%' + @search + '%' 
 OR bl.b_id LIKE '%' + @search + '%' 
 OR m.m_id LIKE '%' + @search + '%' 
 OR d.d_name LIKE '%' + @search + '%' 
 OR m.m_name LIKE '%' + @search + '%') ";

如果你告诉我们细节有什么问题 - 我们将能够提供更详细的假设:)