使用2列表,第1列标题,第2列值连接表

时间:2015-06-03 19:15:30

标签: mysql join

我有两个表,如下图所示,我想对它们进行连接。第一个表包含事件,第二个表包含这些事件的属性。

Schema

我想写一个将连接下面两个表并在底部创建输出的查询。

这在MySQL中可行吗?这个问题很难谷歌(或者甚至拿出一个标题!),所以如果它是重复的话我会道歉。

现在,我有这个:

SELECT * FROM events e LEFT JOIN event_attributes ea ON e.id = ea.event_id WHERE e.id = 1;

产生2行,一行有time_opened,另一行有time_closed。

编辑:我希望它是动态的,所以我可以添加任意数量的属性,名称成为列的标题,值变为行的值。

4 个答案:

答案 0 :(得分:0)

这里需要2个连接:

SELECT * 
FROM events e 
LEFT JOIN event_attributes ea1 ON e.id = ea1.event_id 
                               and ea1.attribute_name = 'time_opened'
LEFT JOIN event_attributes ea2 ON e.id = ea2.event_id 
                               and ea2.attribute_name = 'time_closed'
WHERE e.id = 1;

答案 1 :(得分:0)

试试这个:

SELECT events.id AS id
,      events.description AS description
,      ea_open.value AS time_opened
,      ea_close.value AS time_closed

FROM   events

LEFT JOIN event_attributes AS ea_open
ON  ea_open.id = events.id
AND ea_open.attribute_name = 'time_opened'

LEFT JOIN event_attributes AS ea_close
ON ea_close.id = events.id
AND ea_close.attribute_name = 'time_closed';

答案 2 :(得分:0)

你必须稍微改变你的表格,但是你可以做一些事情来从这两个表格中选择数据并加入它。

SELECT * FROM events, events_attributes WHERE events.id = event_attribute.id

以下是有关该主题的更多信息的链接:SELECT * FROM multiple tables. MySQL

答案 3 :(得分:0)

你可以试试这个:

SELECT 
  e.*,
  MAX(IF(ea.attribute_name = 'time_opened', ea.attribute_value, NULL)) AS time_opened,
  MAX(IF(ea.attribute_name = 'time_closed', ea.attribute_value, NULL)) AS time_closed
FROM events e 
  LEFT JOIN event_attributes ea ON e.id = ea.event_id 
WHERE e.id = 1
GROUP BY e.id, e.name, e.description;