Mysql内连接在php中搜索

时间:2015-03-09 04:51:53

标签: php mysql search

这是我的选择查询

 $raw_results = mysql_query("SELECT *,student_data.student_id,student_data.image,student_data.firstname, student_data.middleI,
            student_data.lastname, 
            student_data.address, student_data.birthday,
            section.section_name, department.dept_name, year_graduated.year, course.course_name,
            year_graduated.publish_id  FROM student_data        
    INNER JOIN course ON student_data.course_id=course.course_id
    INNER JOIN section ON student_data.section_id=section.section_id
    INNER JOIN department ON student_data.dept_id=department.dept_id
    INNER JOIN year_graduated ON student_data.year_id=year_graduated.year_id WHERE (`firstname` LIKE '%".$query."%') OR (`lastname` LIKE '%".$query."%') OR (`birthday` LIKE '%".$query."%') OR (`section_name` LIKE '%".$query."%') OR (`course_name` LIKE '%".$query."%') OR (`year` LIKE '%".$query."%') OR (`address` LIKE '%".$query."%') AND publish_id=2")  ;

我想只显示student_data,其中year_graduated.publish_id等于2.当我运行上面的代码时,它不会过滤学生的publish_id。

2 个答案:

答案 0 :(得分:2)

我认为括号有错误。 之前打开(firstname LIKE'%"。$ query。"%')并在AND AND publish_id = 2之前结束

喜欢那个

$raw_results = mysql_query("SELECT *,student_data.student_id,student_data.image,student_data.firstname, student_data.middleI,
            student_data.lastname, 
            student_data.address, student_data.birthday,
            section.section_name, department.dept_name, year_graduated.year, course.course_name,
            year_graduated.publish_id  FROM student_data        
    INNER JOIN course ON student_data.course_id=course.course_id
    INNER JOIN section ON student_data.section_id=section.section_id
    INNER JOIN department ON student_data.dept_id=department.dept_id
    INNER JOIN year_graduated ON student_data.year_id=year_graduated.year_id WHERE ((`firstname` LIKE '%".$query."%') OR (`lastname` LIKE '%".$query."%') OR (`birthday` LIKE '%".$query."%') OR (`section_name` LIKE '%".$query."%') OR (`course_name` LIKE '%".$query."%') OR (`year` LIKE '%".$query."%') OR (`address` LIKE '%".$query."%')) AND publish_id=2") 

答案 1 :(得分:0)

当你在mysql中运行连接操作时,你应该在查找字段之前放置表名或别名。确保在*

之前有一个有效的表名

请更改您的查询

SELECT table_name.*, student_data.student_id ... 

请在查找字段前添加表/别名。像

WHERE (`student_data.firstname` LIKE '%".$query."%')

OR

AND year_graduated.publish_id = 2