LEFT JOIN不起作用

时间:2015-11-02 11:56:47

标签: mysql left-join

我需要编写一个SQL查询,它连接三个表。

表格是:

  • Hotels:id |名字| nz |照片|价格|标准| idcountry
  • Countries:id |名称
  • home_promo:id | idhotel

我的查询是:

SELECT 
    h.id, h.name, h.nz, h.photo, h.price, h.standard,
    h.idcountry, k.name as k_name 
FROM hotels as h 
LEFT JOIN coutries AS k ON k.id=h.idcountry 
LEFT JOIN home_promo AS hm ON hm.idhotel=h.id 
WHERE h.publications=1

但它返回酒店表中的所有记录。 有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

如果您只想要那些位于home_promo中的酒店ID,那么

This document is a test document, for testing.
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
    View
</title>

答案 1 :(得分:0)

这应该可以解决问题:

SELECT h.id,h.name,h.nz,h.photo,h.price,h.standard,h.idcountry,k.name as k_name 
FROM hotels as h 
JOIN home_promo AS hm ON hm.idhotel=h.id 
LEFT JOIN coutries AS k ON k.id=h.idcountry 
WHERE h.publications=1

虽然您可能想要从国家/地区中删除LEFT,因为离开它仍然会返回没有匹配国家/地区的酒店的结果。

答案 2 :(得分:0)

如果home_promo和国家/地区的ID匹配,则此查询将起作用

SELECT h.id,h.name,h.nz,h.photo,h.price,h.standard,h.idcountry,k.name as k_name 
FROM hotels as h 
LEFT JOIN coutries AS k ON h.idcountry = k.id 
LEFT JOIN home_promo AS hm ON h.id = hm.idhotel
WHERE h.publications=1