SQL连接超过五个表

时间:2009-07-01 16:12:47

标签: sql mysql join

我有五张桌子:

models:             id, name, specification
models_networks:    id, model_id, network_id
networks:           id, name, description
countries_networks: id, country_id, network_id
countries:          id, countryName, etc, etc
  • models表格通过networksmodels_networks表格相关联,并具有多对多关系。
  • networks表通过countriescountries_networks表格连接,具有多对多关系

我需要执行以下查询,但是我被卡住了:

  

选择将在特定国家/地区使用的所有型号。

例如:说法国有两个网络。 PigNetwork和CowNetwork。我希望得到所有适用于PigNetwork或CowNetwork的模型,基本上是在那个国家以任何方式工作的。

如果我已经说清楚了,有人可以帮忙解决JOIN问题吗?我以前只能加入两张桌子。感谢。

5 个答案:

答案 0 :(得分:3)

有些事情应该有效......

SELECT M.Name As ModelName FROM Countries C
INNER JOIN Countries_Networks CN
ON C.CountryId = CN.CountryId
INNER JOIN Networks N
ON CN.NetworkId = N.NetworkId
INNER JOIN ModelNetworks MN
ON MN.NetworkId = N.NetworkId
INNER JOIN Model M
ON M.ModelId = MN.ModelId
WHERE C.CountryName = 'FRANCE'

答案 1 :(得分:3)

SELECT
  m.name AS model_name,
  c.countryName,
  COUNT(*) AS network_count
FROM
  models                        AS  m
  INNER JOIN models_networks    AS mn ON mn.model_id = m.id
  INNER JOIN networks           AS  n ON n.id = mn.network_id
  INNER JOIN countries_networks AS cn ON cn.network_id = n.id
  INNER JOIN countries          AS  c ON c.id = cn.country_id
WHERE
  c.countryName = 'France'
GROUP BY
  m.name,
  c.countryName

答案 2 :(得分:2)

SELECT  m.id
FROM    model m
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    model_networks mn
        JOIN    countries_networks cn
        ON      cn.network_id = mn.network_id
                AND cn.country_id = @code_of_france
        WHERE   mn.model_id = m.id
        )

这是有效的,因为它在找到第一个合适的网络时返回模型。

确保您拥有以下UNIQUE索引:

model_networks (model_id, network_id)
country_network (country_id, network_id)

答案 3 :(得分:1)

SELECT models.id, models.name, models.specifications JOIN models_networks ON models.id=models_networks.model_id WHERE models_networks.networks_id IN (1,2)

(将1,2替换为您的网络ID)

如果您只是想要模型,看起来不需要两个连接。如果您不知道网络ID或者您需要其他表中的列,则只需要更多联接。但语法却是一样的。您只需从WHERE语句

之前的JOIN <table> ON <field>=<field>开始

答案 4 :(得分:1)

select models.id, models.name, models.specification from models inner join models_networks on models.id = models_network.network_id inner join countries_networks on models_network.network_id = countries_networks.network_id where countries_networks.countryName = 'France'