0

我有 2 个单独工作的查询,但不知道如何将它们组合成一个。

第一个计算一个工厂的可用性,如下所示:

SELECT *, 
(off_time - on_time)/(UNIX_TIMESTAMP('x') - UNIX_TIMESTAMP('y')) AS A
FROM(
 SELECT equipment_id,
  IF(time_on < 'x', UNIX_TIMESTAMP('x'), UNIX_TIMESTAMP(time_on)) AS on_time,
   (CASE  
    WHEN (time_off IS NULL) THEN UNIX_TIMESTAMP(NOW())
    WHEN (time_off > 'y') THEN UNIX_TIMESTAMP('y')
    ELSE UNIX_TIMESTAMP(time_off)
   END) AS off_time
  FROM r) AS T
GROUP BY equipment_id 

但我只想显示被标识为可用于服务的工厂,该工厂存储在单独的表中,所以我认为我必须使用 JOIN,例如:

SELECT r.equipment_id, r.time_on, r.time_off, i.in_service
FROM r
INNER JOIN i
ON r.equipment_id=i.equipment_id

但是,我尝试将两者结合起来以失败告终。我是自学成才,对此非常陌生,因此感谢任何帮助、评论甚至只是对我的查询的一些批评。

4

2 回答 2

1

那么你可以像这样加入它。

SELECT
  *,
  ((off_time - on_time)/(UNIX_TIMESTAMP('x') - UNIX_TIMESTAMP('y'))) AS A
FROM (SELECT
    r.equipment_id,
    i.in_service,
    IF(time_on < 'x', UNIX_TIMESTAMP('x'), UNIX_TIMESTAMP(time_on)) AS on_time,
    (CASE WHEN (time_off IS NULL) THEN UNIX_TIMESTAMP(NOW()) WHEN (time_off > 'y') THEN UNIX_TIMESTAMP('y') ELSE UNIX_TIMESTAMP(time_off) END) AS off_time
      FROM r
    left join i
      ON r.equipment_id = i.equipment_id) AS T
GROUP BY equipment_id
于 2013-02-25T12:41:56.780 回答
0

如果我正确理解您的问题,以下是您要查找的 SQL:

SELECT *, 
(off_time - on_time)/(UNIX_TIMESTAMP('x') - UNIX_TIMESTAMP('y')) AS A, i.in_service
FROM(
 SELECT equipment_id,
  IF(time_on < 'x', UNIX_TIMESTAMP('x'), UNIX_TIMESTAMP(time_on)) AS on_time,
   (CASE  
    WHEN (time_off IS NULL) THEN UNIX_TIMESTAMP(NOW())
    WHEN (time_off > 'y') THEN UNIX_TIMESTAMP('y')
    ELSE UNIX_TIMESTAMP(time_off)
   END) AS off_time
  FROM r) AS T 
INNER JOIN i
ON T.equipment_id=i.equipment_id
GROUP BY T.equipment_id 
于 2013-02-25T12:42:42.150 回答