MySQL multi-table query and its group by group sort

Source: Internet
Author: User

//Multi-table query: Get the latest data before you execute a multi-table query

SELECT * from' Students ' st ' Right JOIN( SELECT * from
(
SELECT * fromGoutongWHEREgoutongs= ' asdf 'ORDER byTimeDESC
  ) asGttGROUP bygtt.name_idORDER byGtt.goutong_timeDESC) GT
on' GT '. ' name_id '=' St '. ' ID ' LIMITTen

//Sort the query by time and then group (group   by)
SELECT * from(SELECT * fromGoutongWHEREGoutongs='asdf' ORDER byTimeDESC) asGttGROUP bygtt.name_idORDER byGtt.timeDESC

Reference: http://blog.csdn.net/shellching/article/details/8292338

With Data sheet comments
------------------------------------------------
| ID | NewsID | Comment | Thetime |
------------------------------------------------
|        1 |         1 |     AAA | 11 |
------------------------------------------------
|        2 |         1 |     BBB | 12 |
------------------------------------------------
|        3 |         2 |     CCC | 12 |

------------------------------------------------

NewSID is the news ID, there are several comments per news comment,thetime is the time to comment

Now you want to see the latest comment for each news article:


SELECT * from Comments GROUP BY NewsID obviously not.


SELECT * from Comments GROUP by NewsID ORDER BY thetime Desc is an out-of-group sort or not


There are two ways to accomplish this:

(1)
Selet Tt.id,tt.newsid,tt.comment,tt.thetime from (
Select Id,newsid,comment,thetime from comments ORDER BY thetime Desc) as TT GROUP by NewsID


(2)
Select Id,newsid,comment,thetime from comments as TT GROUP BY Id,newsid,comment,thetime have
Thetime= (select Max (thetime) from comments where Newsid=tt.newsid)

MySQL multi-table query and its group by group sort

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.