如何在同一个主键上连接3个表?

时间:2016-04-03 06:59:32

标签: mysql

我有3张桌子。表格如下:

表酒店

id(pk)
hotel_code
hotel_name
hotel_address

table hotel_description

id(pk)
hotel_id(fk from table hotel)
hotel_title
hotel_description

table hotel_image

id(pk)
hotel_id(fk from table hotel)
image_title
image_description

我加入3表的查询是这样的:

SELECT a.hotel_code, a.hotel_name, a.address, b.hotel_title, b.hotel_description, c.image_title, c.image_url
FROM hotel a
JOIN hotel_description b ON a.id = b.hotel_id
JOIN hotel_image c ON a.id = c.hotel_id
WHERE a.hotel_code = 'IDJKT_00001'

上面运行查询的结果如下: http://snag.gy/nw541.jpg

它看起来是双重数据

如何解决我的问题?

谢谢

1 个答案:

答案 0 :(得分:0)

没有双重数据,您的酒店有多个描述,并且您的酒店有多个图像,如果您不希望它们出现多次,则必须在3个单独的查询中请求这些图像:< / p>

SELECT a.hotel_code, a.hotel_name, a.address
FROM hotel a
WHERE a.hotel_code = 'IDJKT_00001'

SELECT b.hotel_title, b.hotel_description
FROM hotel a
JOIN hotel_description b ON a.id = b.hotel_id
WHERE a.hotel_code = 'IDJKT_00001'

SELECT c.image_title, c.image_url
FROM hotel a
JOIN hotel_image c ON a.id = c.hotel_id
WHERE a.hotel_code = 'IDJKT_00001'

目前您有一家酒店,您可以通过描述表加入这家酒店。描述表有7行这个酒店,所以此时你将有7行。然后你用图像表连接这7行,你至少有4张图像来自我在图像上看到的图像。这意味着您将获得7 * 4 = 28行。