mysql - 编写一个大的 sql 查询还是通过代码处理它?

标签 mysql ruby-on-rails-3.2

我有 2 个以这种方式构建的表:

Trips
- id
- organization_id REQUIRED
- collaboration_organization_id OPTIONAL
...other useless fields...

Organizations
- id
- name REQUIRED
...other useless fields...

现在我被要求创建此类报告:

I want the sum of all trips for each organization, considering that if they have a collaboration_organization_id it should count as 0.5, obviusly the organization in collaboration_organization_id get a +0.5 too

因此,每当我的行程设置了organization_id 和collaboration_organization_id 时,该行程对于两个组织都计为0.5。如果仅设置了organization_id,则计为1。

现在我的问题由两部分组成:

1.

Is a good idea to "solve" the problem all in SQL?

我已经知道如何通过代码解决它,我目前的想法是“选择所有行程(仅这3个字段)并开始在ruby中计数”。请考虑一下,我正在 Rails 上使用 ruby​​,所以仍然可以有一个很好的理由说“不,因为它只能在 mysql 上运行”。

2.

If point 1 is YES, I have no idea how to count for 0.5 each trip where it's required, because count is a "throw-in-and-do-it" function

最佳答案

我不熟悉 ruby​​ on Rails,但这是使用 MySQL 实现此目的的方法。

示例数据:

CREATE TABLE Trips(
  id int not null primary key,
  organization_id int not null,
  collaboration_organization_id int null
  );

INSERT INTO Trips (id,organization_id,collaboration_organization_id)
VALUES
(1,1,5),
(2,1,1),
(3,1,2),
(4,11,1),
(5,1,null),
(6,2,null),
(7,10,null),
(8,6,2),
(9,1,3),
(10,1,4);

MySQL 查询:

SELECT organization_id,
sum(CASE WHEN collaboration_organization_id IS null THEN 1 ELSE 0.5 End) AS number
FROM Trips
GROUP BY organization_id;

通过以下方式尝试:http://www.sqlfiddle.com/#!2/1b01d/107

编辑:添加协作组织

示例数据:

  CREATE TABLE Trips(
  id int not null primary key,
  organization_id int not null,
  collaboration_organization_id int null
  );

INSERT INTO Trips (id,organization_id,collaboration_organization_id)
VALUES
(1,1,5),
(2,1,1),
(3,1,2),
(4,11,1),
(5,1,null),
(6,2,null),
(7,10,null),
(8,6,2),
(9,1,3),
(10,1,4);


CREATE TABLE Organizations(
  id int auto_increment primary key,
  name varchar(30)
  );

INSERT INTO Organizations (name)
VALUES
("Org1"),
("Org2"),
("Org3"),
("Org4"),
("Org5"),
("Org6"),
("Org7"),
("Org8"),
("Org9"),
("Org10"),
("Org11"),
("Org12"),
("Org13"),
("Org14"),
("Org15"),
("Org16");

MySQL 查询:

SELECT O.id, O.name,
sum(CASE WHEN T.collaboration_organization_id IS null THEN 1 ELSE 0.5 End) AS number
FROM Organizations AS O LEFT JOIN Trips AS T  
ON T.organization_id = O.id OR T.collaboration_organization_id = O.id
WHERE T.collaboration_organization_id = O.id OR O.id = T.organization_id
GROUP BY O.id;

http://www.sqlfiddle.com/#!2/ee557/15

关于mysql - 编写一个大的 sql 查询还是通过代码处理它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14367235/

相关文章:

java - ResultSet getDate() 返回不正确和正确的日期

php - 在 php 中生成带有换行符的 csv 时出现小故障

mysql - 运行delayed_job时出现未知别名错误

ruby-on-rails - 混合backbone.js 路由器和rails Controller

php - Laravel SQL : How to return 0 value if no record exists

php - 选择、检查日期和插入的 MySQL 存储过程

mysql - SQL 检索 sql 查询中的最后一条记录

css - 什么是 CSS 创作框架?

ruby-on-rails - 如何优化 Rails 中页面的重复查询?

ruby-on-rails - Ruby on Rails : How to use scope named 'open' ?