mysql条件输出列,基于MySQL中其他列的查询的条件列

在不修改数据库表结构的情况下,用户询问如何使用SQL查询根据出生日期(DOB)和职位(Job_Title)在结果集中添加一列‘Real_Title’。他们提供了PHP后的解决方案,但寻求更直接的SQL方法。提供的SQL CASE语句解决了这个问题,根据出生年份和职位为用户分配了不同的'Real_Title'值。
摘要由CSDN通过智能技术生成

I'm pretty sure I've seen this somewhere, but I can't find the right terminology so I'm having trouble...

Let's say I have a table with user info (let's also assume that it was created by someone who gets paid more than me, so modifying the schema is not an option.) Among the various columns of user info are columns for DOB and job title. I want a query that, based on what is in those columns, will include an extra column called "Real_Title", for example:

User_id Job_Title DOB

joe_1 manager 01/01/1950

jim_1 associate 01/01/1970

jill_1 associate 01/01/1985

jane_1 manager 01/01/1975

query:

SELECT User_id, Real_Title FROM users

IF (YEAR(DOB) < 1980 AND Job_Title = "manager")

{Real_Title = "Old Fart"}

ELSE IF (YEAR(DOB) < 1980 AND Job_Title = "associate")

{Real_Title = "Old Timer"}

ELSE IF (YEAR(DOB) > 1980 AND Job_Title = "manager")

{Real_Title = "Eager Beaver"}

ELSE IF (YEAR(DOB) > 1980 AND Job_Title = "associate")

{Real_Title = "Slacker"}

I know the above is not only wrong but also coded really inefficient, but I wanted to get the idea across.

Is there a way, without using joins, to populate a column based on information in one or more other columns in the same table?

Currently I'm using something in the PHP script after the results are obtained to channel those results into the groups I want, but if it can be done in the query, that would make porting the query to other scripts and languages much easier.

Thanks!

解决方案select User_id

,case

when (YEAR(DOB) < 1980 AND Job_Title = "manager") then 'Old Fart'

when (YEAR(DOB) < 1980 AND Job_Title = "associate") then 'Old Timer'

when (YEAR(DOB) > 1980 AND Job_Title = "manager") then 'Eager Beaver'

when (YEAR(DOB) > 1980 AND Job_Title = "associate") then 'Slacker'

else 'nobody'

end

as Real_Title

from users

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值