1

我遇到了一个问题,我不知道为什么会给我带来麻烦。

我想使用 DISTINCT 语句从数据库中选择所有报价,因此每个报价 ID 都是唯一的。这是我在 Navicat 上以屏幕截图形式获得的内容:

截图 http://www.dreshar.com/sql.jpg http://www.dreshar.com/sql.jpg

对于看不到图像的任何人,这是选择 - 我的错误在哪里?

SELECT DISTINCT
guf_offers.id as OfferId,
guf_offers.validfrom AS OfferValidFrom,
guf_offers.validtill AS OfferValidTill,
guf_offers.days AS OfferDays,
guf_offers.active,
guf_offers.roomtype1 AS OfferRoomtype1,
guf_offers.roomprice1 AS OfferRoomprice1,
guf_countries.caption AS CountryCaption,
guf_courts.caption AS CourtCaption,
guf_hotels.caption AS HotelCaption,
guf_hotels.id AS HotelId,
guf_hotel_images.image AS HotelImage,
guf_offer_types.caption AS OffertypeCaption,
guf_regions.caption AS RegionCaption,
guf_offers.hoteloncourse AS OfferHotelOnCourse,
guf_offers.wellnessspa AS OfferWellnessSpa,
guf_offers.18hole AS Offer18Hole,
guf_offers.topangebot AS OfferTopangebot
FROM guf_offers , guf_countries , guf_courts , guf_hotels , guf_hotel_images , guf_offer_types , guf_regions
WHERE guf_offers.country_id = guf_countries.id AND guf_offers.court_id = guf_courts.id AND guf_offers.hotel_id = guf_hotels.id AND guf_hotel_images.hotel_id = guf_offers.hotel_id AND guf_offers.offer_type_id = guf_offer_types.id AND guf_offers.region_id = guf_regions.id AND guf_offers.active = 1 AND STR_TO_DATE(guf_offers.validtill, '%d.%m.%Y') > STR_TO_DATE('29.04.2013', '%d.%m.%Y')
4

2 回答 2

2

DISTINCT 返回任何不同的列组合。例如,图像中 OfferId = 89 的前两个实例在 HotelImage 列中显示不同的值,因此这些是 DISTINCT 结果。

于 2013-04-29T16:49:07.033 回答
1

如果您想要不同的 id,那么您可能想要使用group by. 查询看起来像:

SELECT
guf_offers.id as OfferId,
guf_offers.validfrom AS OfferValidFrom,
guf_offers.validtill AS OfferValidTill,
guf_offers.days AS OfferDays,
guf_offers.active,
guf_offers.roomtype1 AS OfferRoomtype1,
guf_offers.roomprice1 AS OfferRoomprice1,
guf_countries.caption AS CountryCaption,
guf_courts.caption AS CourtCaption,
guf_hotels.caption AS HotelCaption,
guf_hotels.id AS HotelId,
guf_hotel_images.image AS HotelImage,
guf_offer_types.caption AS OffertypeCaption,
guf_regions.caption AS RegionCaption,
guf_offers.hoteloncourse AS OfferHotelOnCourse,
guf_offers.wellnessspa AS OfferWellnessSpa,
guf_offers.18hole AS Offer18Hole,
guf_offers.topangebot AS OfferTopangebot
FROM guf_offers , guf_countries , guf_courts , guf_hotels , guf_hotel_images , guf_offer_types , guf_regions
WHERE guf_offers.country_id = guf_countries.id AND guf_offers.court_id = guf_courts.id AND guf_offers.hotel_id = guf_hotels.id AND guf_hotel_images.hotel_id = guf_offers.hotel_id AND guf_offers.offer_type_id = guf_offer_types.id AND guf_offers.region_id = guf_regions.id AND guf_offers.active = 1 AND STR_TO_DATE(guf_offers.validtill, '%d.%m.%Y') > STR_TO_DATE('29.04.2013', '%d.%m.%Y')
group by guf_offers.id

其他列是来自不同行的任意值。group by这使用了对where 列的扩展,select即使它们不在聚合函数或group by子句中。

顺便说一句,您应该学习使用正确的语法在from子句中进行连接。join它使查询更具可读性和可维护性。

于 2013-04-29T17:56:23.447 回答