PHP查询不起作用

时间:2016-04-18 14:34:06

标签: mysql sql-server join

这是有效的:

SELECT *
FROM ((((defect
JOIN project_testcase ON 
defect.Test_Id=project_testcase.Test_Id)
JOIN testcase ON 
defect.Test_Id=testcase.Test_Id)
JOIN project_pm ON 
project_testcase.Project_Id=project_pm.Project_Id)
JOIN employee ON 
employee.Emp_id=project_pm.Emp_id)

然而,这不起作用:

SELECT *
FROM ((((defect
JOIN project_testcase ON 
defect.Test_Id=project_testcase.Test_Id)
JOIN testcase ON 
defect.Test_Id=testcase.Test_Id)
JOIN project_pm ON 
project_testcase.Project_Id=project_pm.Project_Id)
JOIN employee ON 
employee.Emp_id=project_pm.Emp_id)
WHERE Project_Id LIKE '%$categ%'

因为我使用了JOIN表并使用Project_Id加入。这是错误吗?

4 个答案:

答案 0 :(得分:1)

我要做的第一件事是将其粘贴到SQL格式化程序中。这将有助于查找语法错误,并可帮助您查看逻辑错误。我建议freeformatter.com

其次,你可以摆脱括号。

修复

您需要在WHERE中指定要获取Project_Id的表,因为它位于多个表中,但为了清楚起见,我将始终指定它来自哪个表。

select
   *   
from
   defect   
join
   project_testcase         
      on   defect.Test_Id=project_testcase.Test_Id       
join
   testcase      
      on   defect.Test_Id=testcase.Test_Id    
join
   project_pm   
      on   project_testcase.Project_Id=project_pm.Project_Id    
join
   employee   
      on   employee.Emp_id=project_pm.Emp_id    
where
   project_testcase.Project_Id like '%$categ%'

答案 1 :(得分:0)

where子句中的

Project_Id不明确,您需要像对联接一样对其进行定义,即WHERE project_pm.Project_Id like '%$categ%'

答案 2 :(得分:0)

在第二个查询的where子句中,您需要告诉rdbms您要过滤哪个Project_Id字段,因为多个表包含Project_Id字段,例如: <version>1.7.21</version>

答案 3 :(得分:0)

首先删除所有不必要的括号,格式化和别名会在下面显示一个相当简单的查询。

select * --This should really be the columns you actually need instead of all of them
from defect d
join project_testcase ptc on d.Test_Id = ptc.Test_Id
join testcase t on d.Test_Id = t.Test_Id
join project_pm p on ptc.Project_Id = p.Project_Id
join employee e on e.Emp_id = p.Emp_id
where p.Project_Id like '%$categ%'

当然这引出了一个问题,为什么在名为Project_Id的列中有这样的文本?这看起来不像是我的项目ID。由于您使用的是前导通配符,因此您具有nonSARGable查询,因​​此您已消除了该列上的索引搜索功能。