如何加入2个MySQL表以确定连接表是否匹配

时间:2015-12-08 19:14:50

标签: mysql left-join

我有2个MySQL表(国家/地区)和(预订)

我想列出countries的每一行,只是说明reservations是否匹配。

在每个实例中:

  • reservations将有1个匹配的行,或
  • reservations将有许多匹配的行,或
  • reservations将没有匹配的行

所以我想从加入中得到的就是知道是否与reservations匹配。没别了。

这是我的查询声明:

SELECT country.countryID, reservation.citizen
FROM countries AS country
LEFT JOIN (
  SELECT reservationID
  FROM reservations
  LIMIT 1
) AS reservation ON reservation.citizen = country.countryID
ORDER BY reservation.citizen

未知栏' reservation.citizen'在' on'

结论: JOIN无法解决问题。

2 个答案:

答案 0 :(得分:1)

问题在于子选择。请注意,您尚未将字段公民列入预订。

SELECT country.countryID, reservation.citizen
FROM countries AS country
LEFT JOIN (
  SELECT reservationID, citizen
  FROM reservations
  LIMIT 1
) AS reservation ON reservation.citizen = country.countryID
ORDER BY reservation.citizen

另一方面,你为什么要做一个subselect?为什么限制?只查询以下内容会不会更好?

SELECT 
    country.countryID, 
    count(reservation.reservationID)
FROM 
    countries AS country
    LEFT JOIN reservations AS reservation 
    ON country.countryID = reservation.citizen
GROUP BY
    country.countryID
HAVING 
    count(reservation.reservationID) > 0
ORDER BY 
    reservation.citizen
;

答案 1 :(得分:1)

您遇到加入问题,应该是

LEFT JOIN reservations AS reservation ON reservation.citizen = country.countryID
ORDER BY reservation.citizen

OR

LEFT JOIN (
  SELECT *
  FROM reservations
  LIMIT 1
) AS reservation ON reservation.citizen = country.countryID
 ORDER BY reservation.citizen

或者更好的LEFT OUTER JOIN以获得不匹配连接条件的行。

 LEFT OUTER JOIN reservations AS reservation ON reservation.citizen = country.countryID
ORDER BY reservation.citizen