我有两张桌子。一个人的姓名(司机)和一个与他们的驾驶执照(许可证)细节和到期。我需要合并这两个表并列出驱动程序的名称,ID号以及许可证是否已过期。
我有以下内容返回所有带有许可证和到期日的驱动程序,但我想添加一个最终列,根据返回的到期日期(时间戳)声明(已过期/有效)。
SELECT d.name AS 'Driver Name', d.nric AS 'NRIC', l.expiry AS 'Expiry' FROM drivers d, licenses l WHERE d.driverID=licenses.driverID ORDER BY name ASC
我需要添加第四列,评估l.expiry
今天是否“小于”,即过期。
输出应该是这样的:
Driver Name NRIC Expiry Validity
Joe Blooggs 1234 1/1/14 Valid
Joe Blooggy 1235 1/3/14 Invalid
有办法做到这一点吗?
答案 0 :(得分:5)
MySQL 5.5.32架构设置:
CREATE TABLE drivers
(`driverID` int, `name` varchar(11), `nric` int)
;
INSERT INTO drivers
(`driverID`, `name`, `nric`)
VALUES
(1, 'Joe Blooggs', 1234),
(2, 'Joe Blooggy', 1235)
;
CREATE TABLE licenses
(`licenseID` int, `driverID` int, `expiry` int)
;
INSERT INTO licenses
(`licenseID`,`driverID`, `expiry`)
VALUES
(1,1, 1406217600),
(2,1, 1409217600),
(3,1, 1432656000),
(4,2, 1406217600)
;
查询1 :
SELECT d.name AS 'Driver Name', d.nric AS 'NRIC', l.expiry AS 'Expiry',
CASE
WHEN l.expiry < UNIX_TIMESTAMP(NOW()) THEN "Invalid"
ELSE "Valid"
END AS Validity
FROM drivers d
INNER JOIN licenses l ON d.driverID=l.driverID and l.licenseID =
(select licenseID
from licenses l2
where l.driverID = l2.driverID
order by expiry desc limit 1)
<强> Results 强>:
| DRIVER NAME | NRIC | EXPIRY | VALIDITY |
|-------------|------|------------|----------|
| Joe Blooggs | 1234 | 1432656000 | Valid |
| Joe Blooggy | 1235 | 1406217600 | Invalid |
答案 1 :(得分:3)
其他答案建议不需要CASE
:
SELECT d.name, l.expiry < NOW() AS expired
FROM drivers AS d
列expired
将是布尔类型。
使用主机代码显示类似&#34;已过期的字符串&#34;并且&#34;没有过期&#34;基于类似(python)("expired", "active")[row.expired]
的东西。这将节省db-server上有价值的cpu周期和网络带宽。
答案 2 :(得分:1)
SELECT d.name AS 'Driver Name', d.nric AS 'NRIC',
SELECT (sub_l.expiry as 'expiry' FROM licenses sub_l
WHERE sub_l.driverID = d.driverID
AND sub_l.licenseID = l.licenseID),
CASE
WHEN EXISTS(SELECT sub_l.expiry FROM licenses sub_l
WHERE sub_l.driverID = d.driverID
AND sub_l.licenseID = l.licenseID
AND sub_l.expiry > NOW())
THEN 0
ELSE 1
END AS is_expired
FROM drivers d JOIN licences l ON d.driverID = licenses.driverID
GROUP BY d.name, d.nric
ORDER BY d.name ASC
答案 3 :(得分:1)
是的,请使用CASE表达式。
select
d.name
, d.nrci
, l.expiry
, case when l.expiry < current_date then 'Invalid' else 'Valid' end as Validity
...