为了眼前的需要,你可以UNION ALL
将3个表一起作为一个派生表来JOIN
对抗。
SELECT
`c`.`procedure`,
`incurredcharges`.`procedure_no`,
`incurredcharges`.`patient_no`
FROM
incurredcharges
/* UNION ALL the 3 like tables together as a derived table */
INNER JOIN (
SELECT `procedure`, `procedure_no` FROM `charges`
UNION ALL
SELECT `procedure`, `procedure_no` FROM `confinement`
UNION ALL
SELECT `procedure`, `procedure_no` FROM `ultrasound`
) c ON `incurredcharges`.`procedure_no` = c.`procedure_no`
WHERE `incurredcharges`.`patient_no` = 12
但对于未来:
然而,正确的长期解决方案是使用与UNION ALL
子查询中使用的类似结构将所有这些记录插入到统一表中,并使用一个新列来标识它们的来源。
CREATE TABLE unified_charges AS
SELECT `procedure`, `procedure_no`, 'ER' AS `chargetype` FROM `charges`
UNION ALL
SELECT `procedure`, `procedure_no`, 'CONFINEMENT' AS `chargetype` FROM `confinement`
UNION ALL
SELECT `procedure`, `procedure_no`, 'ULTRASOUND' AS `chargetype` FROM `ultrasound`
注意:procedure
是必须用反引号引用的 MySQL 保留关键字,所以我只是引用了所有内容。