1

假设我有以下表结构

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_升级 | ur_by | ur_for | 你的投票 | 你的原因 |
+-----+-----------+--------+--------+---------+---- ---------+
| 4 | 1 | 空 | 4 | 空 | 空 |
+-----+-----------+--------+--------+---------+---- ---------+
| 5 | 1 | 空 | 5 | 空 | 空 |
+-----+-----------+--------+--------+---------+---- ---------+

对于成员 2,我希望看到以下结果

+-----+-----------+--------+--------+---------+---- ---------+
|m_id | m_升级 | ur_by | ur_for | 你的投票 | 你的原因 |
+-----+-----------+--------+--------+---------+---- ---------+
| 4 | 1 | 2 | 4 | 1 | 投票 |
+-----+-----------+--------+--------+---------+---- ---------+
| 5 | 1 | 空 | 5 | 空 | 空 |
+-----+-----------+--------+--------+---------+---- ---------+

对于成员 3,我希望看到以下结果

+-----+-----------+--------+--------+---------+---- ---------+
|m_id | m_升级 | ur_by | ur_for | 你的投票 | 你的原因 |
+-----+-----------+--------+--------+---------+---- ---------+
| 4 | 1 | 3 | 4 | 0 | 投反对票|
+-----+-----------+--------+--------+---------+---- ---------+
| 5 | 1 | 3 | 5 | 0 | 投反对票|
+-----+-----------+--------+--------+---------+---- ---------+

到目前为止,我什么都没试过(除了搜索 StackOverflow),因为我不知道从哪里开始。

注意。这是一个用 PHP 编码的网站,所以如果没有纯 SQL 的解决方案,我可以用 PHP 做

提前致谢

4

1 回答 1

0

您必须joins为此使用

select m1.m_id, m1.m_upgrade,
       ur.ur_by, coalesce(ur.ur_for, m1.m_id) as ur_for, ur.ur_vote, ur.ur_reason
from members m1
join members m2 on m2.m_id <> m1.m_id
left join upgrade_reasons ur on ur.ur_by = m2.m_id and ur.ur_for = m1.m_id
where m1.m_upgrade = 1

SQLFiddle用于测试。

于 2013-03-18T16:05:42.030 回答