【问题标题】:Two querys in one [MYSQL] ONE RESULTS两个查询合二为一 [MYSQL] ONE RESULTS
【发布时间】:2017-09-29 10:44:56
【问题描述】:

你们能帮我把两个查询合二为一吗? 这是我的第一个查询:

SELECT estimated_sum_all, story_point_sum_all, time_spent,  reg_date
FROM burndown_snap_all  WHERE project_id='72'

结果:

 | estimated_sum_all | story_point_sum_all | time_spent | reg_date |
 | 300               | 20                  | 20.30      | 2017-09  |
 | 300               | 20                  | 19.30      | 2017-09  |
 | 300               | 20                  | 18.30      | 2017-09  |
 | 300               | 20                  | 15.32      | 2017-09  |

这是我的第二个查询:

SELECT time_spent FROM status_history_hours where
project_id = '72'

结果:

| time_spent | 
| 20.30      |
| 20.30      |
| 20.30      |
| 20.30      |

我想做的是构建一个 mysql 查询,该查询必须包含从第二个查询到 time_spent 的 select/join。决赛桌应该是这样的:

 | estimated_sum_all | story_point_sum_all | time_spent | reg_date |
 | 300               | 20                  | 20.30      | 2017-09  |
 | 300               | 20                  | 20.30      | 2017-09  |
 | 300               | 20                  | 20.30      | 2017-09  |
 | 300               | 20                  | 20.30      | 2017-09  |

问候,

解决方案如下:

SELECT t1.id, t1.estimated_sum_all, 
t1.story_point_sum_all, t1.time_spent, 
t2.id, t2.time_spent FROM 
burndown_snap_all t1, status_history_hours 
t2 WHERE t1.project_id = 72 AND 
t2.project_id = 72 group by t1.id 

但是如何同时按t2.id分组???

【问题讨论】:

  • 也许您在第二个表中有其他有用的列。

标签: mysql join


【解决方案1】:
SELECT estimated_sum_all, story_point_sum_all, time_spent,  reg_date
FROM burndown_snap_all  WHERE project_id='72'
UNION ALL
SELECT time_spent FROM status_history_hours where
project_id = '72'

【讨论】:

  • 使用的 SELECT 语句的列数不同 :)
【解决方案2】:

根据您提供的数据,您可以从第二个表中获取任何匹配值。所以,你可以这样做:

SELECT bsa.estimated_sum_all, bsa.story_point_sum_all, bsa.time_spent,
       bsa.reg_date,
       (SELECT MAX(shh.time_spent)
        FROM status_history_hours shh
        WHERE shh.project_id = bsa.project_id
       ) as time_spent
FROM burndown_snap_all bsa
WHERE project_id = 72;

【讨论】:

  • 可以,但是第二个表中的 times_spent 可以包含不同的值。
  • @ValeriusRomulus 。 . .我建议您用更合适的样本数据和如何进行匹配的解释来问 another 问题。如果您更改此问题,您将使此答案无效,这可能会导致投反对票。
  • project_id 是这两个表的唯一一个公共列。表具有相同数量的记录。只想加入只为结果而花费的时间。
  • SELECT bsa.estimated_sum_all, bsa.story_point_sum_all, bsa.time_spent, bsa.reg_date, (SELECT shh.time_spent FROM status_history_hours shh WHERE shh.project_id = bsa.project_id) as time_spent FROM burndown_snap_all bsa WHERE project_id = 72;会很好,但是这个返回:#1242 - 子查询返回超过 1 行
猜你喜欢
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
  • 1970-01-01
相关资源
最近更新 更多