在mysql中使用where和inner join

时间:2009-09-08 07:24:30

标签: mysql inner-join

我有三张桌子。

地点

ID   | NAME | TYPE |
1    | add1 | stat |
2    | add2 | coun | 
3    | add3 | coun |
4    | add4 | coun | 
5    | add5 | stat | 

学校

 ID | NAME  
 1  | sch1     
 2  | sch2
 3  |sch3 

school_locations

 ID |LOCATIONS_ID |SCHOOL_ID
 1  | 1           |1
 2  | 2           |2
 3  | 3           |3

此处的表位置包含应用程序的所有位置。学校的位置由ID调用。

当我使用查询时

select locations.name from locations where type="coun";

它显示类型为“coun”的名称

但我想显示locations.name,其中只有school_locations有type =“coun”

我尝试了以下查询,但似乎都没有工作

select locations.name 
from locations 
where type="coun" 
inner join school_locations 
   on locations.id=school_locations.location_id 
inner join schools 
   on school_locations.school.id=schools.id;

select locations.name 
from locations 
inner join school_locations 
   on locations.id=school_locations.location_id 
inner join schools 
   on school_locations.school.id=schools.id  where type="coun";

是否可以在查询中使用多个内部联接,还是有其他方式?

4 个答案:

答案 0 :(得分:53)

    SELECT `locations`.`name`
      FROM `locations`
INNER JOIN `school_locations`
        ON `locations`.`id` = `school_locations`.`location_id`
INNER JOIN `schools`
        ON `school_locations`.`school_id` = `schools_id`
     WHERE `type` = 'coun';

WHERE子句必须位于语句的末尾

答案 1 :(得分:2)

试试这个:

SELECT Locations.Name, Schools.Name
FROM Locations
INNER JOIN School_Locations ON School_Locations.Locations_Id = Locations.Id
INNER JOIN Schools ON School.Id = Schools_Locations.School_Id
WHERE Locations.Type = "coun"

您可以将地点加入School_Locations,然后将School_Locations加入学校。这形成了一组所有相关的位置和学校,然后您可以使用WHERE子句将其置于那些位置类型为“coun”的人。

答案 2 :(得分:1)

试试这个:

SELECT
    (
      SELECT
          `NAME`
      FROM
          locations
      WHERE
          ID = school_locations.LOCATION_ID
    ) as `NAME`
FROM
     school_locations
WHERE
     (
      SELECT
          `TYPE`
      FROM
          locations
      WHERE
          ID = school_locations.LOCATION_ID
     ) = 'coun';

答案 3 :(得分:-1)

您可以根据需要使用任意数量的联接,但是,使用的越多,它对性能的影响就越大