我有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无法解决问题。
答案 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