Performing a query on a result from another query?

前端 未结 4 1592
死守一世寂寞
死守一世寂寞 2020-12-29 03:19

I have a the query:

SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=r         


        
相关标签:
4条回答
  • 2020-12-29 04:00

    Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:

    SELECT COUNT(*), SUM(SUBQUERY.AGE) from
    (
      SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
      FROM availables
      INNER JOIN rooms
      ON availables.room_id=rooms.id
      WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
      GROUP BY availables.bookdate
    ) AS SUBQUERY
    
    0 讨论(0)
  • 2020-12-29 04:03

    Note that your initial query is probably not returning what you want:

    SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age 
    FROM availables INNER JOIN rooms ON availables.room_id=rooms.id 
    WHERE availables.bookdate BETWEEN  '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate
    

    You are grouping by book date, but you are not using any grouping function on the second column of your query.

    The query you are probably looking for is:

    SELECT availables.bookdate AS Date, count(*) as subtotal, sum(DATEDIFF(now(),availables.updated_at) as Age)
    FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
    WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
    GROUP BY availables.bookdate
    
    0 讨论(0)
  • 2020-12-29 04:05

    You just wrap your query in another one:

    SELECT COUNT(*), SUM(Age)
    FROM (
        SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age
        FROM availables
        INNER JOIN rooms
        ON availables.room_id=rooms.id
        WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
        GROUP BY availables.bookdate
    ) AS tmp;
    
    0 讨论(0)
  • 2020-12-29 04:22

    I don't know if you even need to wrap it. Won't this work?

    SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
    FROM availables
    INNER JOIN rooms    ON availables.room_id=rooms.id
    WHERE availables.bookdate BETWEEN '2009-06-25' 
      AND date_add('2009-06-25', INTERVAL 4 DAY)
      AND rooms.hostel_id = 5094
    GROUP BY availables.bookdate);
    

    If your goal is to return both result sets then you'll need to store it some place temporarily.

    0 讨论(0)
提交回复
热议问题