如何区分从一个表中选择并将另一个表中的信息添加到结果中?

时间:2012-09-08 20:20:48

标签: mysql sql join

Theres我的两张桌子:

mysql> desc riddims;
+---------------+--------------+------+-----+-------------------+-------+
| Field         | Type         | Null | Key | Default           | Extra |
+---------------+--------------+------+-----+-------------------+-------+
| riddim        | varchar(255) | NO   | MUL | NULL              |       |
| genre         | varchar(9)   | NO   |     | NULL              |       |
| youtube       | varchar(11)  | NO   |     | NULL              |       |
| image         | varchar(11)  | NO   |     | NULL              |       |
| last_modified | timestamp    | NO   |     | CURRENT_TIMESTAMP |       |
+---------------+--------------+------+-----+-------------------+-------+
5 rows in set (0.00 sec)

mysql> desc tunes;
+---------------+--------------+------+-----+-------------------+-------+
| Field         | Type         | Null | Key | Default           | Extra |
+---------------+--------------+------+-----+-------------------+-------+
| riddim        | varchar(255) | NO   | MUL | NULL              |       |
| artist        | varchar(255) | NO   | MUL | NULL              |       |
| tune          | varchar(255) | NO   |     | NULL              |       |
| label         | varchar(255) | NO   |     | NULL              |       |
| producer      | varchar(255) | NO   |     | NULL              |       |
| year          | varchar(4)   | NO   |     | NULL              |       |
| lyrics        | text         | NO   |     | NULL              |       |
| flag          | varchar(12)  | NO   |     | NULL              |       |
| last_modified | timestamp    | YES  |     | CURRENT_TIMESTAMP |       |
+---------------+--------------+------+-----+-------------------+-------+

到目前为止我得到的是

SELECT DISTINCT riddim FROM tunes WHERE year = '2012' ORDER BY last_modified DESC LIMIT 20

它打印'riddim'列的最后20个添加/修改的条目。如何从'riddims'表中将每个riddim的正确信息添加到从'tunes'表中抓取的每一行?

我假设我必须使用“riddim”列以某种方式加入它们,因为这是两个表共有的“关键”,我只是想不通它是如何工作的。

我的目标是打印今年最后20个riddims条目的“riddim,year,image,label”(使用php),其中只有'tunes'表包含有关年份和标签的信息。

1 个答案:

答案 0 :(得分:1)

SELECT DISTINCT
  tunes.riddim AS riddim,
  tunes.year AS year.
  riddims.image AS image,
  runes.label AS label
FROM riddims
INNER JOIN tunes ON riddims.riddim=tunes.riddim
WHERE tunes.year="2012"
ORDER BY riddims.last_modified
LIMIT 20
;