我根据您的图像构建了一个架构。这就是我想出的:
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');