合并两个表并在列中分配1/0

时间:2016-01-11 12:38:23

标签: mysql sql join

我创建了两个表,如下所示:

CREATE TABLE IF NOT EXISTS `tools` (
  `pk_id` int(11) NOT NULL AUTO_INCREMENT,
  `id` int(11) NOT NULL,
  `title` varchar(13) DEFAULT NULL,
  PRIMARY KEY (`pk_id`));

CREATE TABLE IF NOT EXISTS `features` (
  `pk_id` int(11) NOT NULL AUTO_INCREMENT,
  `id` int(11) NOT NULL,
  `feature` varchar(13) DEFAULT NULL,
  PRIMARY KEY (`pk_id`),
  FOREIGN KEY (id) REFERENCES tools(id));

每个工具可能有多个功能。此外,每个功能可能属于不同的工具。在这种情况下,没有第3个表就完成了多对多关系。使用不同的主键重复功能。

现在我想写一个SELECT语句来查看每个工具的所有相应功能,如下所示:

Tools  Feature1 Feature2 Feature3 Feature4
=========================================
ToolA  1        0        0        1
ToolB  0        0        1        0

我该怎么做?

目前我写了这个陈述,但它没有分配1或0,具体取决于特定工具的功能。

SELECT tools.title, features.feature
FROM tools
INNER JOIN features
ON tools.id=features.id;

更新:

根据@sagi的评论,我检查了以下link,并尝试根据我的需要调整代码:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(pa.feature = ''',
      feature ,
      ''', pa.feature , NULL)) AS ',
      feature 
    )
  ) INTO @sql
FROM features;

SET @sql = CONCAT('SELECT p.id
                    , p.title
                    , ', @sql, ' 
                   FROM tools p
                   LEFT JOIN features AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

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

但是我收到了一个错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '8,MAX(IF(pa.feature = 'feature 2', pa.feature, NULL)) AS ' at line 3 

1 个答案:

答案 0 :(得分:1)

SELECT tools.title,
       MAX(case when features.feature = 'Feature1' then 1 else 0 end) as Feature1,
       MAX(case when features.feature = 'Feature2' then 1 else 0 end) as Feature2,
       MAX(case when features.feature = 'Feature3' then 1 else 0 end) as Feature3
FROM tools
INNER JOIN features
ON tools.id = features.id
group by tools.title