选择曲目和具有最大访问次数的日期

时间:2013-04-29 06:30:25

标签: mysql

这是合约。我有两张桌子

tracks

+--------------+------------------+------+-----+---------+----------------+
| Field        | Type             | Null | Key | Default | Extra          |
+--------------+------------------+------+-----+---------+----------------+
| track_id     | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| artist_id    | int(11)          | YES  |     | NULL    |                |
| genre_id     | int(11)          | YES  |     | NULL    |                |
| track_artist | varchar(255)     | YES  |     | NULL    |                |
| track_title  | varchar(255)     | NO   |     | NULL    |                |
| track_lyric  | text             | YES  |     | NULL    |                |
| track_video  | varchar(255)     | YES  |     | NULL    |                |
| play_url     | varchar(255)     | YES  |     | NULL    |                |
| shares       | int(11)          | NO   |     | 0       |                |
| likes        | int(11)          | NO   |     | 0       |                |
| dislikes     | int(11)          | NO   |     | 0       |                |
| is_active    | enum('T','F')    | NO   |     | T       |                |
| created_at   | int(10)          | YES  |     | NULL    |                |
+--------------+------------------+------+-----+---------+----------------+

track_visits

+----------------+------------------+------+-----+---------+----------------+
| Field          | Type             | Null | Key | Default | Extra          |
+----------------+------------------+------+-----+---------+----------------+
| track_visit_id | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| track_id       | int(11)          | NO   | MUL | NULL    |                |
| ip_address     | varchar(255)     | NO   |     | NULL    |                |
| created_at     | int(10)          | YES  |     | NULL    |                |
+----------------+------------------+------+-----+---------+----------------+

问题是: 如何为每个特定曲目选择所有曲目和最大访问次数的日期?

此致

Nasko

1 个答案:

答案 0 :(得分:0)

由于您使用的是MySql,因此可以使用:

SELECT tracks.*, track_visits.*
FROM
  tracks LEFT JOIN (
    SELECT track_id, MAX(created_at) MaxCreatedAt
    FROM track_visits
    GROUP BY track_id) mx
  ON tracks.track_id=mx.track_id
  LEFT JOIN track_visits
  ON mx.track_id=track_visits.track_id
     AND mx.MaxCreatedAt=track_visits.created_at
GROUP BY
  tracks.track_id