我的WHERE子句不尊重条件

时间:2014-07-29 21:39:20

标签: php mysql sql

使用联接(教师表和链接(桥)表)我正在尝试检索教师姓名

MYSQL表格

1。)我有一个链接(桥接)表:我在这里插入关系

 Table Name "cl_st_tch"
 +-------------+-------------+-------------+---------------+
 | classes_id  | students_id | teachers_id |  company_id   |
 +-------------+-------------+-------------+---------------+
 | 1           | 1           | 2           | 1             |
 | 1           | 2           | 4           | 1             |
 | 1           | 3           | 4           | 1             |
 | 1           | 4           | 4           | 1             |
 | 1           | 5           | 4           | 1             |
 +-------------+-------------+-------------+---------------+

2。)这是我的教师表:存储教师名字的简单表

 Table Name "teachers"
 +-------------+-------------+
 |id           | name        |
 +-------------+-------------+  
 | 1           | Sandra      |
 | 2           | Alex        |
 | 3           | Kinder      |
 | 4           | Michael     |
 +-------------+-------------+

MYSQL QUERY

 SELECT 
 DISTINCT teachers.name, teachers.id, cl_st_tch.teachers_id 
 FROM teachers, cl_st_tch 
 WHERE teachers.id && cl_st_tch.teachers_id = 4 

“渴望”的结果

我希望这只能生成1个Name = Michael

“未完成”结果

相反,我得到了所有教师的名字

桑德拉
亚历克斯
金德
迈克尔

我错过了什么?任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

SELECT 
  DISTINCT teachers.name, teachers.id, cl_st_tch.teachers_id 
  FROM teachers
  INNER JOIN cl_st_tch
    ON teachers.id = cl_st_tch.teachers_id
  WHERE teachers.id = 4 

答案 1 :(得分:1)

您的查询在逻辑上无效:

WHERE teachers.id && cl_st_tch.teachers_id = 4

更改为:

WHERE teachers.id = cl_st_tch.teachers_id and teachers.id = 4