查询连接上的最大值

时间:2012-08-04 09:23:24

标签: mysql sql join syntax

如何获取max MESSAGENUMBER

mysql> 
mysql> describe ARTICLE;describeNEWSGROUP;
+---------------+------------+------+-----+---------+----------------+
| Field         | Type       | Null | Key | Default | Extra          |
+---------------+------------+------+-----+---------+----------------+
| ID            | bigint(20) | NO   | PRI | NULL    | auto_increment |
| MESSAGENUMBER | int(11)    | YES  |     | NULL    |                |
| NEWSGROUP_ID  | bigint(20) | YES  | MUL | NULL    |                |
+---------------+------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| ID        | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| NEWSGROUP | varchar(255) | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> 
mysql> select * from ARTICLE left join NEWSGROUP on ARTICLE.NEWSGROUP_ID=NEWSGROUP.ID where NEWSGROUP.newsgroup = "gwene.com.economist";
+----+---------------+--------------+------+---------------------+
| ID | MESSAGENUMBER | NEWSGROUP_ID | ID   | NEWSGROUP           |
+----+---------------+--------------+------+---------------------+
| 18 |             4 |            4 |    4 | gwene.com.economist |
| 19 |             5 |            4 |    4 | gwene.com.economist |
| 20 |             6 |            4 |    4 | gwene.com.economist |
| 21 |             7 |            4 |    4 | gwene.com.economist |
| 22 |             8 |            4 |    4 | gwene.com.economist |
| 23 |             9 |            4 |    4 | gwene.com.economist |
| 24 |            10 |            4 |    4 | gwene.com.economist |
| 25 |            11 |            4 |    4 | gwene.com.economist |
+----+---------------+--------------+------+---------------------+
8 rows in set (0.00 sec)

mysql> 

2 个答案:

答案 0 :(得分:1)

select * from ARTICLE left join NEWSGROUP 
on ARTICLE.NEWSGROUP_ID=NEWSGROUP.ID 
where NEWSGROUP.newsgroup = "gwene.com.economist" 
ORDER BY MESSAGENUMBER DESC LIMIT 1

答案 1 :(得分:1)

SELECT MAX(MESSAGENUMBER)
FROM ARTICLE left join NEWSGROUP on ARTICLE.NEWSGROUP_ID=NEWSGROUP.ID 
WHERE NEWSGROUP.newsgroup = "gwene.com.economist"