合并2个表并显示给定成员的所有可能结果

时间:2013-03-18 15:35:16

标签: php mysql

假设我有以下表结构

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实现它

提前致谢

1 个答案:

答案 0 :(得分: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进行测试。