SQL连接和左外连接:为什么结果不同?

时间:2013-04-02 22:08:55

标签: mysql sql

我有一张桌子partenaire。 partenaire可能有一个或多个地址。当然,一个地址可能“属于”不止一个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,结果就不一样了:

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不为null,所以如果你执行“JOIN”或“LEFT OUTER JOIN”,结果应该是相同的。或者我错过了什么?

1 个答案:

答案 0 :(得分:4)

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