MySQL - 选择带有连接表的查询到一行

时间:2014-02-23 16:32:22

标签: mysql sql select join

我有以下表格:

**entries**
entry_id | date | engineer | project

**entries_allowanes_map**
entry_id | allowance_id

**allowances**
allowance_id | allowance_name

我想创建一个SELECT查询,它将产生以下结果:

entry_id | date | engineer | project | allowance_name1 | allowance_name2 | allowance_name_n...

我试过的查询为一个条目注册的每个津贴返回一行。我只想要一行,并附上所有许可。

提前致谢

3 个答案:

答案 0 :(得分:0)

我建议用group_concat()做这件事。它不会将值放在单独的列中,但它会将给定条目的所有内容放在一行中:

select e.entry_id, e.date, e.engineer, e.project, 
       group_concat(a.allowance_name) as allowances
from entries e join
     entries_allowances_map f
     on e.entry_id = eam.entry_id 
     allowances a
     on eam.allowance_id = a.allowance_id
group by e.entry_id;

答案 1 :(得分:0)

以下是我的查询:

它会在不同的列中输出您的预期结果:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      '(SELECT max(CASE WHEN AL.ALLOWANCE_ID = ''',
      ALLOWANCE_ID,
      ''' THEN 1 END) AS `',
      ALLOWANCE_ID, '` FROM entries_allowanes_map AL WHERE E.ENTRY_ID = AL.ENTRY_ID ) AS `',
      ALLOWANCE_NAME, '`'
    )
  ) INTO @sql
FROM allowances;



SET @sql 
  = CONCAT('SELECT E.ENTRY_ID, E.DATE, E.ENGINEER, E.PROJECT, ', @sql, ' 
           FROM entries as e');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

以下是SqlFiddle

答案 2 :(得分:-1)

尝试

SELECT * FROM entries as e
INNER JOIN entries_allowanes_map as a ON e.entry_id=e.entry_id
INNER JOIN allownces as al ON al.allownce_id=a.allowance_id