0

Sorry about the confusing title. Couldnt come up with better.

Well I have table messages with fields id, from, to, message

Lets say there are messages from John and Nate for Dave

so it would look like that

id|from|to|message
1|John|Dave|Hey    
2|Nate|Dave|Yooo    
3|John|Dave|Sup    
4|Nate|Dave|Waazza

Imagine there is more of them tho.

Ok I want to extract messages for Dave and I do it like that

SELECT * FROM messages WHERE ˙to` = 'Dave' ORDER BY id ASC

Ok all fine but this shows messages from both John and Nate.

Is there a way I could extract messages only from either(one) of them? Like I would extract only messages from John.

I am aware of doing another WHERE statement but I am looking for solution where I know only for who are messages not from who

4

3 回答 3

1

在不知道 from 的情况下,您可以使用子查询,例如:

SELECT * 
    FROM messages 
   WHERE `to` = 'Dave' AND 
         `from` = (SELECT `from` 
                     FROM messages 
                    WHERE `to` = 'Dave'
                    LIMIT 1)
ORDER BY id ASC;

使用最小值:

SELECT * 
    FROM messages 
   WHERE `to` = 'Dave' AND 
         `from` = (SELECT MIN(`from`)
                     FROM messages 
                    WHERE `to` = 'Dave'
                    LIMIT 1)
ORDER BY id ASC;

使用 MAX:

SELECT * 
    FROM messages 
   WHERE `to` = 'Dave' AND 
         `from` = (SELECT MAX(`from`)
                     FROM messages 
                    WHERE `to` = 'Dave'
                    LIMIT 1)
ORDER BY id ASC;

在子查询中,您可以使用MAX/MIN函数来获得不同。

以上所有查询的实时演示。

注意:这是因为您知道要查找消息的 2 个人的姓名。

您可以使用ANDto和获取与名称匹配的数据from

  SELECT * 
    FROM messages 
   WHERE `to` = 'Dave' AND
         `from` = 'John' 
ORDER BY id ASC;

现场演示。

或者您可以将以下内容用于两者的所有消息:

  SELECT * 
    FROM messages 
   WHERE (`to` = 'Dave' AND
         `from` = 'John') OR
         (`to` = 'John' AND
         `from` = 'Dave')
ORDER BY id ASC;

现场演示。

于 2013-08-09T18:27:17.670 回答
1
SELECT * FROM message WHERE `to` = 'Dave' 
AND `from` IN (SELECT MIN(`from`) FROM message WHERE `to` = 'Dave') ORDER BY id ASC; 

这是你想要的 ?

演示

于 2013-08-09T18:29:25.777 回答
-2

顺便说一句,您正在混合 ' (单引号)和 ` (反引号)。 看这里

至于您的问题,您可以使用AND.

SELECT * FROM messages WHERE `to`='Dave' AND `from`='John' ORDER BY id ASC

现在它只显示来自 John 的消息!

于 2013-08-09T18:26:07.777 回答