11

我有一张桌子partenaire。合伙人可能有一个或多个地址。当然,一个地址可能“属于”多个合伙人。所以我有 3 个表partenairepartenaire_adresseadresse。该地址只有一个城镇(ville法语),所以我id_ville在表中有一个外键addresse

SELECT
    p.nom,
    v.nom, v.id_region as id_r, v.id_departement as id_p,
    r.description as region
FROM partenaire p
JOIN partenaire_adresse pa
    ON pa.id_partenaire=p.id
JOIN adresse a
    ON a.id=pa.id_adresse
JOIN ville v
    ON v.id=a.id_ville
JOIN region r
    ON v.id_region=r.id
LIMIT 4;

这给了我这些结果:

+----------------------------+-------------+------+------+--------+
| nom                        | nom         | id_r | id_p | region |
+----------------------------+-------------+------+------+--------+
| Ferme Auberge Christlesgut | Breitenbach |    1 |    2 | Alsace | 
| Alice Pizza                | Strasbourg  |    1 |    1 | Alsace | 
| Au Vieux Cellier           | Strasbourg  |    1 |    1 | Alsace | 
| Auberge du 7Eme Art        | Strasbourg  |    1 |    1 | Alsace | 
+----------------------------+-------------+------+------+--------+

现在,如果我LEFT OUTER JOIN在最后一张表 ( region) 上执行 a ,结果将不一样:

SELECT
    p.nom,
    v.nom, v.id_region as id_r, v.id_departement as id_p,
    r.description as region
FROM partenaire p
JOIN partenaire_adresse pa
    ON pa.id_partenaire=p.id
JOIN adresse a
    ON a.id=pa.id_adresse
JOIN ville v
    ON v.id=a.id_ville
LEFT OUTER JOIN region r
    ON v.id_region=r.id
LIMIT 4;

不一样的结果。看:

+---------------------+----------+------+------+----------------+
| nom                 | nom      | id_r | id_p | region         |
+---------------------+----------+------+------+----------------+
| 'Le 144' Petrossian | Paris 18 |   12 |   43 | Île-de-France  | 
| 'Le 144' Petrossian | Paris 08 |   12 |   43 | Île-de-France  | 
| 'O'Quai'            | Vouvray  |    7 |   26 | Centre         | 
| 'O'Quai'            | Tours    |    7 |   26 | Centre         | 
+---------------------+----------+------+------+----------------+

我认为不应该,因为在第一个查询中,id_region 和 id_departement 不为空,所以如果你做一个“JOIN”或“LEFT OUTER JOIN”,结果应该是一样的。还是我错过了什么?

4

1 回答 1

4

您遇到的问题与没有指定顺序时 SQL 不保证结果的顺序有关。如果添加 ORDER BY 子句,则应该得到相同的结果,前提是表在所有行上都有匹配的键(当然)。

于 2013-04-02T22:16:55.517 回答