我有这张桌子:
------------------------------
|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
答案 0 :(得分: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
答案 1 :(得分:0)
你应该看一个加入。
select * from table1 inner join table2 using (`ID`) where job_code = ....
然后你有一行将两个表连接在一起
还使用mysql_ *函数,不再维护这些函数请更新到mysqli_ *或PDO。
此外,您需要转义查询,等待在该代码中发生的SQL注入攻击
答案 2 :(得分: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% "
答案 3 :(得分:0)
你的SQL查询错误试试这个
SELECT * FROM works WHERE works.ID=employee.ID AND
employee.employee_code=".$_GET['employee_code']."
答案 4 :(得分: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
获得更清晰的结果