如何使用 Join 仅从另一个表中获取一条记录


How to get only one record from another table using Join

我有一张酒店桌子。另外,我有一个酒店图像表.对于特定的酒店,酒店图像表中将有多个图像。

只需要获取所有酒店的单个图像,同时使用左连接,我正在获取特定酒店的所有图像。我只需要一张所有酒店的照片。

酒店餐桌

    CREATE TABLE IF NOT EXISTS `tbl_hotel` (
  `int_hotel_id` int(11) NOT NULL auto_increment,
  `str_country_id` varchar(5) NOT NULL,
  `str_hotel_name` varchar(20) default NULL,
  `int_property_type_id` int(11) default NULL,
  `int_hotel_theme_id` int(11) default NULL,
  `str_hotel_facility` varchar(50) default NULL,
  `str_star_category` varchar(10) default NULL,
  `str_web_url` varchar(30) default NULL,
  `str_hotel_mail_id` varchar(25) default NULL,
  `txt_hotel_description` text,
  `str_hotel_city_name` varchar(50) default NULL,
  `str_hotel_address` text NOT NULL,
  `str_hotel_address2` text NOT NULL,
  `int_hotel_zip_code` varchar(20) default NULL,
  `str_hotel_phone` varchar(20) default NULL,
  `str_hotel_fax_no` varchar(20) default NULL,
  `bit_allow_booking` tinyint(4) default NULL,
  `bit_active` tinyint(4) NOT NULL default '0',
  `str_account_type` varchar(200) NOT NULL,
  PRIMARY KEY  (`int_hotel_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=95 ;

酒店形象

CREATE TABLE IF NOT EXISTS `tbl_hotel_image` (
  `int_image_id` int(11) NOT NULL auto_increment,
  `str_image_name` varchar(50) default NULL,
  `txt_image_description` text,
  `int_hotel_id` int(11) default NULL,
  `bit_main_image` tinyint(4) default NULL,
  `bit_active` tinyint(4) default NULL,
  PRIMARY KEY  (`int_image_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=119 ;

连接绑定了两个表,但 [GROUP BY] 的作用类似于记录压缩,获取具有相同值的记录,在这种情况下,它只从 tbl_hotel_imgage.int_hotel_id 获取一条记录 这里 在这里,你可以找到这个语句的更多信息。

    Select * from 
         tbl_hotel inner join tbl_hotel_image on 
         tbl_hotel_image.int_hotel_id=tbl_hotel.int_hotel_id
    Group by
        tbl_hotel_image.int_hotel_id;
select * from (
select * from tbl_hotel h 
  join (select 
               int_image_id, 
               str_image_name,       
               @curRank := @curRank + 1 AS rank 
        from tbl_hotel_image,(SELECT @curRank := 0) r
ORDER BY  image_id) img
    on h.int_hotel_id = img.int_hotel_id
) q 
where rank = 1