使用外键:使用id列从另一个表中获取列

时间:2016-08-03 04:00:26

标签: mysql

我对SQL很陌生,所以我还没有冒险进入多表用法。

以下是我的表格:

客户表 - >

CREATE TABLE IF NOT EXISTS player_table (
player_id SMALLINT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
playername varchar(40) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
PRIMARY KEY (player_id),
UNIQUE KEY playername (playername)
) 
COLLATE latin1_general_ci, ENGINE = INNODB

数据表 - >

CREATE TABLE Data_table ( 
data_id int(10) UNSIGNED NOT NULL AUTO_INCREMENT, 
timestamp datetime NOT NULL, 
player_id SMALLINT(6) UNSIGNED NOT NULL, 
action TINYINT(3) UNSIGNED NOT NULL, 
data varchar(400) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL, 
PRIMARY KEY (data_id), 
KEY timestamp (timestamp), 
KEY player (player_id)
) COLLATE latin1_general_ci, ENGINE = INNODB;

我要做的是将player_idplayer_table链接到我的SELECT声明。因此,当我从Data_table中选择所有数据时,我希望得到一个playername而不是player_id与其余数据Data_table相关联。无论如何有效地做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以根据需要使用左连接或内连接

    SELECT 
      D.*,
      P.playername 
    FROM Data_table D
    LEFT JOIN player_table P ON P.player_id=D.player_id