0

我有这张桌子:

------------------------------
|ID | name   | employee_code |
------------------------------
|24 | Robert |    20234      |
------------------------------

-------------------------------------
|ID |   job_code   |     team       |
-------------------------------------
|24 | 241124 | Robert, Eduard, Etc. |
-------------------------------------

我想按员工代码在第二个表中搜索,我尝试这样的事情:

$sql=mysql_query("SELECT * FROM works WHERE (SELECT name FROM employee WHERE employee_code LIKE '%".$_GET['employee_code']."%' AS searchname) team Like %searchname% ");

结果:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
4

5 回答 5

2

试试这个查询 -

$employee_code = mysql_real_escape_string($_GET['employee_code']);

$sql=mysql_query("SELECT w.* 
                  FROM employee e
                  JOIN works w 
                  ON w.team LIKE CONCAT('%', e.name ,'%')
                  WHERE employee_code LIKE '%$employee_code%'");

看到这个 SQLFiddle 例子 - http://sqlfiddle.com/#!2/8f8b7/1

于 2013-07-09T08:24:34.297 回答
0

您的 SQL 查询错误 试试这样

 SELECT * FROM works WHERE works.ID=employee.ID AND 
   employee.employee_code=".$_GET['employee_code']."
于 2013-07-09T08:00:39.660 回答
0

您应该查看 join 。

select * from table1 inner join table2 using (`ID`) where job_code = ....

然后你有 1 行,两个表连接在一起

还有你使用 mysql_* 函数,这些不再维护,请更新到 mysqli_* 或 PDO。

您还需要逃避您的查询,该代码中等待发生 SQL 注入攻击

于 2013-07-09T07:59:15.217 回答
0

这可能会告诉你究竟出了什么问题。

$sql=mysql_query("SELECT * FROM works WHERE (SELECT name FROM employee WHERE employee_code LIKE '%".$_GET['employee_code']."%' AS searchname) team Like %searchname% ");
if (!$sql)
    echo mysql_error();

你不应该只是假设你的查询已经工作,然后继续在另一个命令中使用该资源,而不检查它是否确实有效。

您不应该做的另一件事是将用户输入直接放入 SQL 查询中,而无需任何形式的转义,因为这将使任何人都可以完全控制您的数据库。

SELECT * FROM works WHERE (SELECT name FROM employee WHERE employee_code LIKE '%".mysql_real_escape_string($_GET['employee_code'])."%' AS searchname) team Like %searchname% "
于 2013-07-09T07:59:42.137 回答
0
SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.employee_code = t2.job_code

或者

SELECT t1.id, t1.name, t2.team FROM table1 t1 INNER JOIN table2 t2 ON t1.employee_code = t2.job_code

为了更干净的结果

于 2013-07-09T08:09:27.873 回答