我有两个表格,我想以特定的方式将它们连接在一起。我希望得到的结果是:
然而,返回的是以下内容:
site statusname total
2 Follow-Up 0
2 Off Study 0
2 Screening 1
2 Treatment 0
1 Follow-Up 0
1 Off Study 0
1 Screening 2
1 Treatment 0
然而,返回的是以下内容:
site statusname total
1 Follow-Up 0
1 Off Study 0
1 Screening 2
2 Screening 1
1 Treatment 0
我实际的查询(返回错误结果的那个)看起来像这样:
SELECT
sitestatus.site AS site,
sitestatus.statusname AS statusname,
count(participant.id) AS total
FROM
(SELECT DISTINCT
participant.`site` AS site,
participant_status.`name` AS statusname,
participant_status.`id` AS status
FROM
participant_status
CROSS JOIN
participant) AS sitestatus
LEFT JOIN
participant
ON
participant.`site` = sitestatus.`site` AND
participant.`status` = sitestatus.`status`
GROUP BY
sitestatus.`statusname`,
participant.`site`
然而,如果我进行轻微(但不可接受)的修改,将一个WHERE
子句添加到子查询中并使用UNION
,我就可以得到所需的结果。以下是查询:
SELECT
sitestatus.site AS site,
sitestatus.statusname AS statusname,
count(participant.id) AS total
FROM
(SELECT DISTINCT
participant.`site` AS site,
participant_status.`name` AS statusname,
participant_status.`id` AS status
FROM
participant_status
CROSS JOIN
participant
WHERE site=1) AS sitestatus
LEFT JOIN
participant
ON
participant.`site` = sitestatus.`site` AND
participant.`status` = sitestatus.`status`
GROUP BY
sitestatus.`statusname`,
participant.`site`
UNION
SELECT
sitestatus.site AS site,
sitestatus.statusname AS statusname,
count(participant.id) AS total
FROM
(SELECT DISTINCT
participant.`site` AS site,
participant_status.`name` AS statusname,
participant_status.`id` AS status
FROM
participant_status
CROSS JOIN
participant
WHERE site=2) AS sitestatus
LEFT JOIN
participant
ON
participant.`site` = sitestatus.`site` AND
participant.`status` = sitestatus.`status`
GROUP BY
sitestatus.`statusname`,
participant.`site`;
我无法弄清楚我的遗失行去了哪里。
以下是相关的模式:
CREATE TABLE `participant` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`site` int(10) unsigned NOT NULL,
`status` int(10) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
)
并且
CREATE TABLE `participant_status` (
`id` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
感谢您能提供任何帮助。
(编辑:现在按照Tim的建议使用 CROSS JOIN
。)