[英]Join tables according to a column of the table
I have a table which stores the important dates. 我有一张存储重要日期的表格。
importantDateType
column can be either 1 or 2. Given that this is a dropdown in the front-end. importantDateType
列可以为1或2。鉴于这是前端的下拉列表。
I have separate two tables to store Electorate Division & Village details. 我有两个单独的表格来存储选举区和乡村的详细信息。 What I do is store in
importantDateParent
is the ID of the either Electorate Division or Village. 我要做的就是店
importantDateParent
是要么选民司或村的ID。
My problem is if the a particular record's importantDateType
is 1, important dates table should join with Electorate Division table and get the name of the Electorate Division. 我的问题是,特定记录的
importantDateType
日期类型是否为1,重要日期表应与选举部门表联接,并获得选举部门的名称。 if the a particular record's importantDateType
is 2, important dates table should join with Village table and get the name of the Village. 如果特定记录的
importantDateType
为2,则重要日期表应与Village表联接,并获得Village的名称。
What I'm using right now is 我现在正在使用的是
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'
I don't want to have two columns like tbl_elecdivision
. 我不
tbl_elecdivision
这样有两列。 elecDivName
and tbl_villages
. elecDivName
和tbl_villages
。 villageName
. villageName
。 How can I have column called importantDateTypeName
which contains the name of the Electorate Division or Village depending on importantDateType
being 1 or 2 ? 我怎么能有一个名为
importantDateTypeName
列,其中包含根据importantDateType
DateType为1或2的选举区或乡村的名称?
did you try using a case ... when ... in your select clause 您是否尝试过使用case ... when ...在select子句中
you should something like this: 您应该是这样的:
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.