0

这是我的简单查询:

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!

我究竟做错了什么?

4

3 回答 3

2

你可以试试:

Select user_id, body 
from Messages where (author = 'john' and receipt = 'erick') or
(author = 'erick' and receipt = 'john')

顺便说一句,由于您只从一个表中选择数据,因此您不必在每次引用字段时都指定其名称。

于 2013-08-28T16:18:59.800 回答
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条件。

于 2013-08-29T13:28:58.557 回答
0

您可以通过更改 where 条件来做到这一点:

Select body
from Messages 
    where 
(messages.author = 'john' and messages.receipt = 'erick') 
or 
(messages.author = 'erick' and messages.receipt = 'john')
于 2013-08-28T16:19:06.120 回答