簡體   English   中英

根據表的列聯接表

[英]Join tables according to a column of the table

我有一張存儲重要日期的表格。

在此處輸入圖片說明

importantDateType列可以為1或2。鑒於這是前端的下拉列表。

  • 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這樣有兩列。 elecDivNametbl_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM