MYSQL内连接和派生表

时间:2013-02-25 12:07:31

标签: mysql

我有两个单独工作的查询,但无法弄清楚如何将它们合并为一个。

第一个计算一件植物的可用性,如下:

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

然而,我试图将两者结合起来导致失败。我是自学而且非常新的,所以对我的疑问提出任何帮助,评论或甚至一些批评都是值得赞赏的。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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