[英]Join tables according to a column of the table
我有一張存儲重要日期的表格。
importantDateType
列可以為1或2。鑒於這是前端的下拉列表。
我有兩個單獨的表格來存儲選舉區和鄉村的詳細信息。 我要做的就是店importantDateParent
是要么選民司或村的ID。
我的問題是,特定記錄的importantDateType
日期類型是否為1,重要日期表應與選舉部門表聯接,並獲得選舉部門的名稱。 如果特定記錄的importantDateType
為2,則重要日期表應與Village表聯接,並獲得Village的名稱。
我現在正在使用的是
SELECT `tbl_importantdates`.*,
`tbl_elecdivision`.`elecDivName`,
`tbl_villages`.`villageName`
FROM (`tbl_importantdates`)
LEFT JOIN `tbl_elecdivision` ON `tbl_importantdates`.`importantDateParent` = `tbl_elecdivision`.`elecDivID`
LEFT JOIN `tbl_villages` ON `tbl_importantdates`.`importantDateParent` = `tbl_villages`.`villageID`
WHERE `tbl_importantdates`.`status` = '1'
我不tbl_elecdivision
這樣有兩列。 elecDivName
和tbl_villages
。 villageName
。 我怎么能有一個名為importantDateTypeName
列,其中包含根據importantDateType
DateType為1或2的選舉區或鄉村的名稱?
您是否嘗試過使用case ... when ...在select子句中
您應該是這樣的:
select `tbl_importantdates`.*,
case when importantdatetype = 1 then tbl_elecdivision.elecDivName,
case when importantdatetype = 2 then tbl_villages. villageName
else 'nothing' end name
--.......rest of code your comes here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.