问题:根据文档编号搜索员工。 输入:文件清单。和文档类型 预期结果:相应文档号 AND 类型的员工列表。
我有的表:表1:员工 empID - person
表2:文件 docNo - docType - id
请注意:employee.person.id = doc.parent.id - 数据库设计也是如此 写了这样的查询:
SELECT employee
from Employee employee, Document doc
WHERE doc.docType IN :docTypeList
and doc.docNo IN :docNoList
and employee.person.id = doc.parent.id
我知道它不会起作用,因为" doc.docType IN:docTypeList和doc.docNo IN:docNoList",但无法想到替代方案。任何导致修改查询,以便我可以处理docTypeList和docNoList来查找匹配它们的员工。
答案 0 :(得分:1)
看起来您只需要在ID值上加入表格,并在select子句中添加正确的值:
SELECT a.employee, b.docType, b.docNo
FROM employee a JOIN document b
ON a.empID=b.id
这是一个使用原始问题中的命名约定(类型)的示例:
SELECT emp.employee, doc.docType, doc.docNo
FROM Employee emp JOIN document doc
ON emp.empID=doc.id
与您的问题无关,但在使用tablename别名时,您应该缩短别名,否则您每次都可以输入表的名称。别名的要点是通过使用缩短的表名使代码更清晰,更容易键入。见上文 - 我将员工别名更改为" emp"
答案 1 :(得分:0)
我有更多的SQL服务器,所以假设你的列表参数就像tableTypes ....
SELECT employee
from Employee employee
INNER JOIN Document doc ON doc.parent.id = employee.person.id
WHERE
doc.docType IN ( Select doctype FROM :docTypeList )
and doc.docNo IN (Select doc no FROM :docNoList )
答案 2 :(得分:0)
当您需要将参数列表传递给IN()时,解决方案是分解列表并将每个项目作为单独的参数传递给SQL语句。
假设MySQL + PDO:
$paramCount = 0;
$params = []; // holds parameter values
$typesParamNames = $numbersParamNames = []; // parameter names for each list
// document types
foreach ($docTypeList as $val)
{
++$paramCount;
$paramName = ":p{$paramCount}";
$params[$paramName] = $val;
$typesParamNames[] = $paramName;
}
// document numbers
foreach ($docNoList as $val)
{
++$paramCount;
$paramName = ":p{$paramCount}";
$params[$paramName] = $val;
$numbersParamNames[] = $paramName;
}
// build the SQL
$typesSqlFragment = implode(',', $typesParamNames);
$numbersSqlFragment = implode(',', $numbersParamNames);
$sql = "SELECT employee from Employee employee, Document doc WHERE doc.docType IN ($typesSqlFragment) and doc.docNo IN ($numbersSqlFragment) and employee.person.id = doc.parent.id";
$stmt = $dbh->prepare($sql);
// pass the collected parameters values to the prepared statement
foreach ($params as $name => $val) {
$stmt->bindParam($name, $val);
}
// run it
$stmt->execute();