SELECT 'q1' AS source, a, b, c, d FROM t1 WHERE ...
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2 JOIN t3 ON ...
UNION ALL
SELECT 'q3', '1', '2', buckle, my_shoe FROM t4
SELECT t.a
, SUM(t.b)
, AVG(t.c)
FROM (
SELECT 'q1' AS source, a, b, c, d FROM t1
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
) t
GROUP BY t.a
ORDER BY t.a
如果您的问题是这样的--选择ename、DNAME from emp、Department,而不使用联接..
然后,我会做这个..。
SELECT ename, (SELECT dname
FROM dept
WHERE dept.deptno=emp.deptno)dname
FROM EMP
产出:
ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
ENAME DNAME
---------- --------------
JAMES SALES
FORD RESEARCH
MILLER ACCOUNTING
14 rows selected.
Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join. In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.
select
(
select s.state_name from state s where s.state_id=3
) statename,
(
select c.description from country c where c.id=5
) countryname
from dual;
where dual is a dummy table with single column--anything just require table to view
In this case we are assuming that we have two tables: SMPPMsgLogand SMSService with common column serviceid:
SELECT sp.SMS,ss.CMD
FROM vas.SMPPMsgLog AS sp,vas.SMSService AS ss
WHERE sp.serviceid=5431
AND ss.ServiceID = 5431
AND Receiver ="232700000"
AND date(TimeStamp) <='2013-08-07'
AND date(TimeStamp) >='2013-08-06' \G;
10条答案
按热度按时间6vl6ewon1#
你可以试着这样做:
nwwlzxa72#
UNION ALL
运算符可能就是您要找的。使用此运算符,您可以将多个查询的结果集连接在一起,保留每个查询的所有行。请注意,
UNION
运算符(不带ALL
关键字)将消除结果集中存在的任何“重复”行。UNION ALL
操作符保留每个查询的所有行(并且可能执行得更好,因为它没有执行重复检查和删除操作的开销)。在每个查询中,列数和每列的数据类型必须匹配。如果其中一个查询的列比另一个多,我们有时会在另一个查询中包含伪表达式,以使列和数据类型“匹配”。通常,在每个返回文字的查询的选择列表中包含一个表达式(一个额外的列)会很有帮助,以揭示哪些查询是该行的“源”。
您可以将这样的查询放在一组括号中,并将其用作内联视图(或者MySQL行话中的“派生表”),这样您就可以对所有行执行聚合操作。
23c0lvtd3#
你可以试试这个记号:
一个更复杂的问题:
这类查询通常称为“隐式联接”,Explicit vs implicit SQL joins询问两者如何比较。在某些情况下,隐式查询执行计划与显式联接相同。
wi3ka0sx4#
如果您的问题是这样的--选择ename、DNAME from emp、Department,而不使用联接..
然后,我会做这个..。
产出:
afdcj2ne5#
You should try this
sc4hvdpw6#
SELECT * from table1 UNION SELECT * FROM table2
whitzsjs7#
Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join.
In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.
where dual is a dummy table with single column--anything just require table to view
yrwegjxp8#
select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;
h22fl7wq9#
In this case we are assuming that we have two tables:
SMPPMsgLog
andSMSService
with common columnserviceid
:hsvhsicv10#
you can try this works always for me