使用distinct仅检索指定字段的一行

时间:2013-03-31 17:38:31

标签: mysql

SELECT SUBSTRING(m.content,1,20) as content, 
       m.viewed, m.sent_date, 
       u.username 
FROM message m 
INNER JOIN user u 
ON u.userid = m.message_from
WHERE m.message_to = :userid

我对此查询的问题是它从同一用户名中选择多行。我只想让它为每个用户名选择一行。

我相信我使用DISTINCT?

我无法让它工作,有人可以帮助我!

感谢。

2 个答案:

答案 0 :(得分:1)

SELECT SUBSTRING(m.content,1,20) as content, m.viewed, m.sent_date, u.username 
FROM message m INNER JOIN user u ON u.userid = m.message_from
WHERE m.message_to = :userid GROUP BY u.userid

答案 1 :(得分:-1)

是的!您可以在用户名中使用distinct

SELECT Distinct( u.username ), SUBSTRING(m.content,1,20) as content, 
       m.viewed, m.sent_date           
FROM message m 
INNER JOIN user u 
ON u.userid = m.message_from
WHERE m.message_to = :userid