0

我有 2 个相同的表格,它们具有相同的格式但填充了不同的数据。

我想SELECT使用group by并且order by不想使用 a进行查询,UNION因为它使我的查询很长。

这是一个有效的示例:

(SELECT a, b, c, d, e, f, g, MIN(h) as h, i 
 FROM `table1` 
 WHERE a LIKE '%this%' AND b LIKE '%that%' 
 GROUP BY b, a,c) 
UNION 
(SELECT a, b, c, d, e, f, g, MIN(h) as h, i 
 FROM `table2` 
 WHERE a LIKE '%this%' AND b LIKE '%that%' 
 GROUP BY b, a,c) 
ORDER BY 
    b DESC, h ASC, c ASC

有没有更优雅的方式来使查询工作?

就像是

(SELECT a, b, c, d, e, f, g, MIN(h) as h, i 
 FROM `table1`,`table2` 
 WHERE a LIKE '%this%' AND b LIKE '%that%' 
 GROUP BY b, a, c) 
ORDER BY 
    b DESC, h ASC, c ASC`
4

1 回答 1

2

你想要的是union all一个子查询:

SELECT a, b, c, d, e, f, g, MIN(h) as h, i
FROM ((select table1.*
       from table1
      ) union all
      (select table2.*
       from table2
      )
     ) t
WHERE a LIKE '%this%' AND b LIKE '%that%'
GROUP BY b, a,c
order by b DESC, h ASC, c ASC

我假设查询只是代表,因为您e, f, g, i没有select聚合函数。

于 2012-12-06T15:44:35.833 回答