MySQL使用另一个表中的值创建临时字段

时间:2013-07-08 20:25:29

标签: mysql sql

您好我对基本的SQL命令非常熟悉,但我希望在执行此查询时提供一些帮助,这对我来说似乎太复杂了。不确定它是否可能。

我会尝试解释我想做的事:/

基本上我想在查询中创建额外的字段,如果在另一个表中找到正确的条件,它将显示'on'。

表A包含用户的数据。表B包含成就,并通过ID链接。

有不同类型的成就,有些得到批准和拒绝。我正在尝试将已批准的成就分类到与该类型对应的临时字段中。

我提供了一个我正在尝试做的例子。 Click here to view image因为有点难以解释。我也试图在MySQL上这样做。

任何建议或意见将不胜感激。非常感谢尼克

1 个答案:

答案 0 :(得分:0)

我根据您的图片构建了一个架构。这就是我想出的:

SELECT
  a.id,
  a.first_name,
  a.surname,
  if (b1.type is null, '', 'on') as A1,
  if (b2.type is null, '', 'on') as A2,
  if (b3.type is null, '', 'on') as A3
FROM `a`
  LEFT JOIN `b` as b1 ON a.id = b1.uid AND b1.type = 1 AND b1.status = 'accepted'
  LEFT JOIN `b` as b2 ON a.id = b2.uid AND b2.type = 2 AND b2.status = 'accepted'
  LEFT JOIN `b` as b3 ON a.id = b3.uid AND b3.type = 3 AND b3.status = 'accepted'
GROUP BY a.id;

结果:

+----+------------+-----------+----+----+----+
| id | first_name | surname   | A1 | A2 | A3 |
+----+------------+-----------+----+----+----+
|  1 | john       | smith     | on |    |    |
|  2 | david      | russel    | on | on |    |
|  3 | james      | duncan    | on |    | on |
|  4 | gavin      | dow       | on | on |    |
+----+------------+-----------+----+----+----+

这是我使用的数据:

--
-- Table structure for table `a`
--

CREATE TABLE IF NOT EXISTS `a` (
  `id` int(10) unsigned NOT NULL,
  `first_name` varchar(32) NOT NULL,
  `surname` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `a`
--

INSERT INTO `a` (`id`, `first_name`, `surname`) VALUES
(1, 'john', 'smith'),
(2, 'david', 'russel'),
(3, 'james', 'duncan'),
(4, 'gavin', 'dow');

--
-- Table structure for table `b`
--

CREATE TABLE IF NOT EXISTS `b` (
  `id` int(10) unsigned NOT NULL,
  `uid` int(10) unsigned NOT NULL,
  `type` int(10) NOT NULL,
  `status` varchar(32) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `b`
--

INSERT INTO `b` (`id`, `uid`, `type`, `status`) VALUES
(1, 1, 1, 'accepted'),
(2, 2, 1, 'accepted'),
(3, 2, 2, 'accepted'),
(4, 4, 1, 'accepted'),
(5, 4, 2, 'accepted'),
(6, 4, 3, 'declined'),
(7, 3, 1, 'accepted'),
(8, 3, 2, 'declined'),
(9, 1, 2, 'declined'),
(10, 3, 3, 'accepted');