将两个SQL语句合并为一个的最佳方法是什么?
SELECT MIN(capacity) AS mincapacity, MAX(capacity) AS maxcapacity
FROM room
SELECT MIN(grade) AS mingrade, MAX(grade) AS maxgrade
FROM room_grade
提前致谢!
答案 0 :(得分:4)
鉴于两个结果集每个只包含一行,最简单的方法是交叉连接:
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
答案 1 :(得分:3)
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
这里的主要好处是将所有记录放在一行上,而不是加入每个表的组件记录。
在聚合之前涉及联接的答案将引入显着的开销,这将对性能产生巨大影响。
答案 2 :(得分:1)
SELECT 'CAPACITY', MIN(capacity) AS min, MAX(capacity) AS max
FROM room
UNION
SELECT 'GRADE', MIN(grade) AS min, MAX(grade) AS max
FROM room_grade
应该做的。
答案 3 :(得分:1)
你可以用可怕的JOIN
语法:
SELECT MIN(capacity) AS mincapacity, MAX(capacity) AS maxcapacity, MIN(grade) AS mingrade, MAX(grade) AS maxgrade
FROM room, room_grade;
但是你应该使用正确的JOIN
语法
SELECT MIN(r.capacity) AS mincapacity, MAX(r.capacity) AS maxcapacity
, MIN(rg.grade) AS mingrade, MAX(rg.grade) AS maxgrade
FROM room r
JOIN room_grade rg
ON r.key = rg.key; (whatever the key is that joins the two tables)
答案 4 :(得分:1)
EITHER
SELECT MIN(capacity) AS mincapacity, MAX(capacity) AS maxcapacity FROM room
UNION ALL
SELECT MIN(grade) AS mingrade, MAX(grade) AS maxgrade FROM room_grade
OR
SELECT MIN(r.capacity) AS mincapacity, MAX(r.capacity) AS maxcapacity,
MIN(rg.grade) AS mingrade, MAX(rg.grade) AS maxgrade
FROM room r
INNER JOIN room_grade rg ON r.Id = rg.room_id
答案 5 :(得分:1)
您想要加入ID字段。我假设'room'表有一个唯一的key字段,room_grade可以有相同的字段。加入两个这样的东西。
SELECT MIN(r.capacity) AS mincapacity, MAX(r.capacity) AS maxcapacity, MIN(g.grade) AS mingrade, MAX(g.grade) AS maxgrade
FROM room r
inner join room_grade g
on room r.roomId = g.roomId