首页 > 代码库 > 关于SQL的相关笔记【长期更新,只发一帖】

关于SQL的相关笔记【长期更新,只发一帖】

场景【1】多表联查时,主表与关联表同时与同一张(第三张表)有关联,类似三角恋关系- -


涉及表:

  • HOUSE:记录了房屋信息
  • ROOMS:记录了房间信息
  • HOUSE_STATUS:记录了状态信息的中文字段

房屋信息HOUSE表中有一个关于记录房屋状态的字段,status_id,与HOUSE_STATUS的主键表关联,而房间信息ROOMS表中,也有一个关于记录房屋状态的字段,也是status_id,当HOUSE与ROOMS建立关联查询时,两张表又分别需要与HOUSE_STATUS这张表建立关联查询。则出现了标题说的三角恋关系,查询方式只需要利用别名查询即可:

SELECT
  HOUSE.ID,
  HOUSE.NAME,
  HOUSE.FLOOR,
  HOUSE.EXPECT_PRICE,
  HOUSE.AREA_NUMBER,
  HOUSE.HAVE_KITCKEN,
  HOUSE.HAVE_BALCONY,
  PROVINCE.provinceName,
  CITY.cityName,
  AREA.areaName,
  COMMUNITY.ID             community_ID,
  COMMUNITY.NAME           community_Name,
  HOUSE_LAYOUT.NAME        layout_Name,
  DECORATION_TYPE.NAME     decorationType_Name,
  HOUSE_STATUS.STATUS_NAME houseStatus_Name,
  PAYMENT.PAYMENT_NAME     payment_Name,
  RENT_MODE.ID             rentMode_ID,
  RENT_MODE.NAME           rentMode_Name,
  ROOMS.ID,
  ROOMS.ROOM_NO,
  ROOMS.HOUSE_STATUS_ID,
  ROOMS.AREA_NUMBER,
  ROOMS.EXPECT_PRICE,
  ROOMS.HAVE_WASHROOM,
  ROOMS.HAVE_KITCKEN,
  ROOMS.HOUSE_STATUS_ID,
  ROOMS.HAVE_DESK,
  ROOMS.HAVE_AIRCONDITIONING,
  ROOMS.HAVE_WARDROBE,
  ROOMS.HAVE_WATERHEATER,
  ROOMS.HAVE_WLAN,
  rooms_Status.ID          rooms_StatusID,
  rooms_Status.STATUS_NAME rooms_StatusName
FROM HOUSE
  JOIN PROVINCE ON HOUSE.PROVINCE_ID = PROVINCE.provinceID
  JOIN CITY ON HOUSE.CITY_ID = CITY.cityID
  JOIN AREA ON HOUSE.AREA_ID = AREA.areaID
  JOIN COMMUNITY ON HOUSE.COMMUNITY_ID = COMMUNITY.ID
  JOIN HOUSE_LAYOUT ON HOUSE.LAYOUT_ID = HOUSE_LAYOUT.ID
  JOIN DECORATION_TYPE ON HOUSE.DECORATION_TYPE_ID = DECORATION_TYPE.ID
  JOIN HOUSE_STATUS ON HOUSE.HOUSE_STATUS_ID = HOUSE_STATUS.ID
  JOIN PAYMENT ON HOUSE.EXPECT_PAYMENT_ID = PAYMENT.ID
  JOIN HOUSE_RENT_MODE ON HOUSE.ID = HOUSE_RENT_MODE.HOUSE_ID
  JOIN RENT_MODE ON HOUSE_RENT_MODE.RENT_MODE_ID = RENT_MODE.ID
  JOIN ROOMS ON HOUSE.ID = ROOMS.HOUSE_ID
  JOIN HOUSE_STATUS rooms_Status ON ROOMS.HOUSE_STATUS_ID = rooms_Status.ID
WHERE HOUSE.ID = 1

 

关于SQL的相关笔记【长期更新,只发一帖】