如何通过join从表中检索数据

时间:2018-03-21 09:48:49

标签: mysql sql

我正在使用DROP TABLE IF EXISTS `events_dictionary`; CREATE TABLE `events_dictionary` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(64) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `events_dictionary` VALUES (1, 'Light'),(2, 'Switch'),(3, 'on'),(4, 'off'); DROP TABLE IF EXISTS `events_log`; CREATE TABLE `events_log` ( `log_id` bigint(20) NOT NULL AUTO_INCREMENT, `event_name_id` int(11) NOT NULL DEFAULT '0', `event_param1` int(11) DEFAULT NULL, `event_value1` int(11) DEFAULT NULL, PRIMARY KEY (`log_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `events_log` VALUES (1, 1, 2, 3),(2, 1, 2, 4); 。里面有两张桌子:

events_dictionary

events_log events names,params and values包含event_log的名称。

所以,我的问题是 - 我如何从event_name_id, event_param1, event_value1表中选择数据name列映射到events_dictionary表中的SELECT name, event_param1, event_value1 FROM events_log JOIN events_dictionary ON events_log.event_name_id = events_dictionary.id; 值?

我尝试过这样的查询:

name  | event_param1  | event_value1
Light | 1             |  1
Light | 1             |  2

但是,在这种情况下,我只看到event_name_id被来自events_dictionary的值替换,如下所示:

{{1}}

我想用event_dictionary中的名字替换event_param1和event_value1。

提前致谢!

2 个答案:

答案 0 :(得分:3)

您需要多次加入events_dictionary

SELECT a.name, b.name, c.name 
FROM events_log 
JOIN events_dictionary a ON events_log.event_name_id = a.id
JOIN events_dictionary b ON events_log.event_param1 = b.id
JOIN events_dictionary c ON events_log.event_value1 = c.id;

PS
您对event_log的示例并非有用,而是插入值(1,1,2,3),(2,1,2,4)以打开和关闭灯的开关。
DS

答案 1 :(得分:1)

您可以使用相关子查询:

SELECT name, 
       (SELECT t.name
       FROM events_dictionary AS t
       WHERE t.id = event_param1) AS param_name, 
       (SELECT t2.name
       FROM events_dictionary AS t2
       WHERE t2.id = event_value1) AS event_name
FROM events_log AS el
JOIN events_dictionary AS ed ON el.event_name_id = ed.id;

Demo here