33

我有三张桌子。

地点

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”的名称

但我想显示只有 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

4 回答 4

69
    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子句必须在语句的末尾

于 2009-09-08T07:28:14.060 回答
3

试试这个:

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”的那些。

于 2009-09-08T07:29:36.357 回答
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';
于 2012-08-16T16:39:11.683 回答
-2

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

于 2009-09-08T07:29:47.073 回答