假设我有以下表结构
DROP TABLE IF EXISTS `members`;
CREATE TABLE `members`
(
m_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT
, m_upgrade TINYINT NOT NULL DEFAULT 0 COMMENT '0 - no upgrade, 1 - possible upgrade'
) ENGINE MyISAM
;
DROP TABLE IF EXISTS `upgrade_reasons`;
CREATE TABLE `upgrade_reasons`
(
ur_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT
, ur_by INT NOT NULL COMMENT 'Who upgraded me'
, ur_for INT NOT NULL COMMENT 'who this upgrade is for'
, ur_vote TINYINT DEFAULT NULL COMMENT 'NULL - not yet voted, 0 - do not upgrade, 1 - upgrade'
, ur_reason VARCHAR(255) DEFAULT NULL COMMENT 'The reason for marking as upgrade / do not upgrade'
, UNIQUE INDEX ur_idx(ur_by, ur_for)
) ENGINE MyISAM
;
INSERT INTO `members`(m_id, m_upgrade)
VALUES
(1, 0)
, (2, 0)
, (3, 0)
, (4, 1)
, (5, 1)
;
INSERT INTO `upgrade_reasons`(ur_by, ur_for, ur_vote, ur_reason)
VALUES
(2, 4, 1, 'Vote for')
, (3, 4, 0, 'vote against')
, (3, 5, 0, 'vote against')
;
对于成员1,我希望看到以下结果
+-----+-----------+-------+--------+---------+-------------+ |m_id | m_upgrade | ur_by | ur_for | ur_vote | ur_reason | +-----+-----------+-------+--------+---------+-------------+ | 4 | 1 | NULL | 4 | NULL | NULL | +-----+-----------+-------+--------+---------+-------------+ | 5 | 1 | NULL | 5 | NULL | NULL | +-----+-----------+-------+--------+---------+-------------+
对于成员2,我希望看到以下结果
+-----+-----------+-------+--------+---------+-------------+ |m_id | m_upgrade | ur_by | ur_for | ur_vote | ur_reason | +-----+-----------+-------+--------+---------+-------------+ | 4 | 1 | 2 | 4 | 1 | Vote for | +-----+-----------+-------+--------+---------+-------------+ | 5 | 1 | NULL | 5 | NULL | NULL | +-----+-----------+-------+--------+---------+-------------+
对于成员3,我希望看到以下结果
+-----+-----------+-------+--------+---------+-------------+ |m_id | m_upgrade | ur_by | ur_for | ur_vote | ur_reason | +-----+-----------+-------+--------+---------+-------------+ | 4 | 1 | 3 | 4 | 0 | vote against| +-----+-----------+-------+--------+---------+-------------+ | 5 | 1 | 3 | 5 | 0 | vote against| +-----+-----------+-------+--------+---------+-------------+
到目前为止,我没有尝试过(除了搜索StackOverflow),因为我没有线索从哪里开始。
NB。这是用PHP编写的网站,所以如果没有纯粹的SQL解决方案,我可以用PHP实现它
提前致谢
答案 0 :(得分:0)