设计数据库并编写分数查询的SQL查询

时间:2019-10-22 14:24:38

标签: sql database algorithm

enter image description here

我正在尝试设计数据库并根据可用的特定条件和选项编写SQL查询以对设备进行评分。

条件,例如:

  • 硬件强度
  • 软件安全性
  • 设备操作系统
Master中给出了每个标准的

选项。根据每个选项,都有一个得分

我试图考虑使用联接的SQL查询,但是由于我是JavaScript开发人员,所以完全不知所措。

这甚至可以在单个SQL查询中完成吗?

3 个答案:

答案 0 :(得分:1)

假设您想要最终分数的总和,则可以使用join。这是一种方法:

select d.*,
       (coalesce(mh.score, 0) + coalesce(ms.score, 0) + coalesce(md.score, 0)) as total_score
from data d left join
     master mh
     on mh.field = 'Hardware Strength' and
        mh.option = d.hardware_strength left join
     master ms
     on msfield = 'Sofware Security' and
        ms.option = d.software_security left join
     master md
     on mh.field = 'Device OS' and
        mh.option = d.device_os;

答案 1 :(得分:1)

如果您稍微tidy up数据库,就可以直接做到这一点:

create table phones (
  id SERIAL PRIMARY KEY,
  model varchar(20) NOT NULL UNIQUE,
  hardware_strength INT NOT NULL,
  software_security INT NOT NULL,
  os INT NOT NULL
);

create table hardware_strength (
  id SERIAL PRIMARY KEY,
  description varchar(20) NOT NULL UNIQUE,
  score INT NOT NULL
);

create table software_security (
  id SERIAL PRIMARY KEY,
  description varchar(20) NOT NULL UNIQUE,
  score INT NOT NULL
);

create table os (
  id SERIAL PRIMARY KEY,
  description varchar(20) NOT NULL UNIQUE,
  score INT NOT NULL
);

有了此模型,查询很简单:

SELECT 
  a.*, 
  b.score + c.score + d.score as score
FROM phones a, hardware_strength b, software_security c, os d
WHERE 
  a.hardware_strength = b.id AND
  a.software_security = c.id AND
  a.os = d.id
;

您可以在此sqlfiddle中玩它。

答案 2 :(得分:1)

使用任意数量的条件设置结构的常规方法如下:

create table phones (pid int identity primary key, pnam varchar(64));
insert into phones (pnam) values ('Google X'),('Samsung P');
create table props  (id int, crit varchar(32),
val varchar(32));
create table scores (critsc varchar(32), valsc varchar(32), score int);
insert into props values (1,'hw','metal'),(1,'sec','high'),(1,'os','android'), (2,'hw','diamond'),(2,'sec','low'),(2,'os','windows');
insert into scores values ('hw','plastic',3),('hw','glas',5),('hw','metal',8),('hw','diamond',10),('sec','low',2),('sec','high',5),('os','windows',4),('os','java',6),('os','meego',7),('os','android',10);

select coalesce(pnam,'ALL MODELS') pnam, 
       coalesce(crit,'total score') crit, 
       case when crit>'' then max(val) else '' end val, sum(score) score
from phones 
inner join props on pid=id
inner join scores on critsc=crit and valsc=val
group by pnam,crit with rollup

输出:

pnam        crit        val      score
Google X    hw          metal    8
Google X    os          android  10
Google X    sec         high     5
Google X    total score          23
Samsung P   hw          diamond  10
Samsung P   os          windows  4
Samsung P   sec         low      2
Samsung P   total score          16
ALL MODELS  total score          39

演示:https://rextester.com/NMKGY74929

诚然,这不是最短的方法,但是它允许使用各种标准和值方案,而不必更改表结构。