首页 > 解决方案 > 选择生肖的 SQL 查询

问题描述

请告诉我 sql 查询按出生日期选择星座。

这是表结构。

CREATE TABLE constellation
    constellation_name VARCHAR(5) PRIMARY KEY,
    start_date INTEGER,
    end_date INTEGER
);

INSERT INTO constellation
    VALUES ('Aries', 321,419), ('Taurus',420 ,520),
           ('Gemini', 521,621), ('Cancer',622 ,722),
           ('Leo', 723,822), ('Virgo',823 ,922)
           ('Libra', 923,1023), ('Scorpio',1024 ,1122),
           ('Sagittarius',1123 ,1221), ('Capricorn', 1222,119),
           ('Aquarius', 120,218), ('Pisces', 219,320);

标签: sql

解决方案


请注意,varchar(5)对于大多数星座来说,这不会让你走得太远。

您可以使用join. 大多数数据库都有 和 之类的功能month()day()尽管它们的名称可能略有不同。

这个想法是:

select t.*, c.constellation_name
from t join
     constellation c
     on month(dob) * 100 + day(dob) between start_mmdd and end_mmdd

编辑:

对付摩羯座:

select t.*, c.constellation_name
from t join
     constellation c
     on (start_mmdd < end_mmdd and 
         month(dob) * 100 + day(dob) between start_mmdd and end_mmdd
        ) or
        (start_mmdd > end_mmdd and 
         (month(dob) * 100 + day(dob) >= start_mmdd or
          month(dob) * 100 + day(dob) <= end_mmdd
        ) ;

推荐阅读