0

嗨,我对基本的 SQL 命令相当熟悉,但我希望在执行这个查询时得到一些帮助,这对我来说似乎太复杂了。不确定它是否可能。

我会尝试解释我想做什么:/

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

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

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

我提供了一个我正在尝试做的例子。单击此处查看图像因为它有点难以解释。我也在尝试在 MySQL 上执行此操作。

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

4

1 回答 1

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');
于 2013-07-08T21:00:02.010 回答