在1个查询中查询3个表 - 错过最后一个

时间:2014-05-15 18:43:35

标签: sql pdo

我希望得到以下结果:

| # | Country | Percent | Nb bookings |
| 1 | France  | 20%     | 10 bookings |
| 2 | Canada  | 80%     | 8  bookings |

我的实际数据库是这样的:

表1: ___ Kardex

  KDX_Id (exemple 9)
  ...
  KDX_PostalAddress_Country (example: FR)

表2: ___预订

  BOO_Id
  BOO_ClientId (link with table 1, = 9)

表3: ___ CountryList

  CTY_Code (link with table 1, = FR)
  CTY_en (should show France)

我在PDO中的SQL查询如下:

SELECT KDX_PostalAddress_Country,
       COUNT(KDX_Id) * 100 /
  (SELECT COUNT(KDX_Id)
   FROM ___Kardex) AS KDX_CountryPercentage,
       COUNT(KDX_Id) AS KDX_CountryCount
FROM ___Kardex
WHERE KDX_HotelId=:hotel_id
GROUP BY KDX_PostalAddress_Country
ORDER BY KDX_CountryPercentage DESC

但是我无法获得国家名称(CTY_en),只是代码(KDX_PostalAddress_Country)。

我尝试插入INNER JOIN但没有成功。

INNER JOIN ___CountryList
ON ___Kardex.KDX_PostalAddress_Country=___CountryList.CTY_Code

你能帮我解决这个问题吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

SELECT CTY_en,
       COUNT(KDX_Id) * 100 /
  (SELECT COUNT(KDX_Id)
   FROM ___Kardex) AS KDX_CountryPercentage,
       COUNT(KDX_Id) AS KDX_CountryCount
FROM ___Kardex
INNER JOIN ___CountryList
ON ___Kardex.KDX_PostalAddress_Country=___CountryList.CTY_Code
WHERE KDX_HotelId=:hotel_id
GROUP BY KDX_PostalAddress_Country
ORDER BY KDX_CountryPercentage DESC