0

我有一张存储重要日期的表格。

在此处输入图像描述

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_villagesvillageName. importantDateTypeName根据importantDateType1 或 2 ,我怎样才能有一个名为包含选举部门或村庄名称的列?

4

1 回答 1

1

您是否尝试在您的选择子句中使用 case ... when ...

你应该是这样的:

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
于 2013-05-25T07:13:19.897 回答