Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two SQL statements

Tags:

sql

What would be the best way to combine the two SQL statements into one?

  SELECT MIN(capacity) AS mincapacity, MAX(capacity) AS maxcapacity 
  FROM room

  SELECT MIN(grade) AS mingrade, MAX(grade) AS maxgrade 
  FROM room_grade

Thanks in advance!

like image 959
CJS Avatar asked Mar 14 '26 04:03

CJS


2 Answers

Given that both resultsets contain only one row each, the simplest way would be a cross join:

select * from
(SELECT MIN(capacity) AS mincapacity, MAX(capacity) AS maxcapacity FROM room) r
cross join
(SELECT MIN(grade) AS mingrade, MAX(grade) AS maxgrade FROM room_grade) g
SELECT
  *
FROM
  (SELECT MIN(capacity) AS mincapacity, MAX(capacity) AS maxcapacity FROM room) AS room
CROSS JOIN
  (SELECT MIN(grade) AS mingrade, MAX(grade) AS maxgrade FROM room_grade) AS room_grade

The main benefits here are having all the records on one row, and not joining the component records of each table.

Answer that involve a join before the aggregation will introduce a significant overhead that will make a massive difference to performance.

like image 39
MatBailie Avatar answered Mar 16 '26 18:03

MatBailie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!