这是我的简单查询:
Select user_id, body
from Messages where (Messages.author = 'john' and Messages.receipt = 'erick'
UNION ALL (Messages.author = 'erick' and Messages.receipt = 'john');
我只想尝试将这两个简单的选择查询结合起来,得到类似的结果:
user_id body
------------------
1 hello
2 hi john
2 hello this is erick
1 this is john!
我做错了什么?
答案 0 :(得分:2)
您可以尝试:
Select user_id, body
from Messages where (author = 'john' and receipt = 'erick') or
(author = 'erick' and receipt = 'john')
顺便说一下,由于您只从一个表中选择数据,因此每次引用字段时都不必指定其名称。
答案 1 :(得分:0)
您可以通过更改您的位置条件来执行此操作:
Select body
from Messages
where
(messages.author = 'john' and messages.receipt = 'erick')
or
(messages.author = 'erick' and messages.receipt = 'john')
答案 2 :(得分:0)
您应该使用以前的答案。我认为他们的表现更好。
我的回答是澄清UNION
关键字:UNION
加入两个行集,应该按如下方式使用:
-- One rowset:
SELECT user_id, body FROM Messages WHERE author = 'john' AND receipt = 'erick'
UNION ALL
- Another rowset:
SELECT user_id, body FROM Messages WHERE author = 'erick' AND receipt = 'john'
; -- Union of both is returned!
但是,如果您要在单个表中查找行,请避免UNION
:只需编写一个符合WHERE
条件。