我有两张桌子:
列
first_name
last_name
列
fname
lname
我有一个输入表单,它将输入的数据输入到输入字段中,并将其传递给以下SQL查询:
select * from student WHERE first_name like '%$q%' OR last_name like '%$q%'
但是,我现在要加入teacher_accounts表,看看输入的名称是否与输入字段中输入的名称相匹配。基本上我需要一个SQL语句,根据输入到输入字段的数据检查teacher_accounts和student表。
感谢您的帮助!
我需要提一下,我正在使用mysql_fetch_array输出这些数据,因此我需要一种方法让脚本能够辨别是否需要从教师列或学生列中提取。
while($row=mysql_fetch_array($result)) {
echo "<a href='?fname=".$row['first_name']."&lname=".$row['last_name']."'>".$row['first_name']." ".$row['last_name']."<br />";
答案 0 :(得分:2)
SELECT first_name, last_name, 'student' as `type`
FROM students
WHERE first_name like '%<your string>%'
OR last_name like '%<your string>%'
UNION
SELECT fname, lname, 'teacher' as `type`
FROM teacher_accounts
WHERE fname like '%<your string>%'
OR lname like '%<your string>%'
有关如何使用占位符安全地准备语句和传递值,请参阅:http://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html。
答案 1 :(得分:1)
SELECT *
FROM (
SELECT
first_name AS `first`,
last_name AS `last`,
'student' AS `typeofaccount`
FROM Student
UNION
SELECT
fname AS `first`,
lname AS `last`,
'teacher' AS `typeofaccount`
FROM teacher_accounts
) AS u
WHERE
first like '%$q%'
OR last like '%$q%'