昨晚我有一个问题,以确保我已正确格式化我的PHP,以确保我能够测试查询。今天在mysql工作台工作时,我发现我无法获得我想要的所有结果。我目前在我的"联系人"表但是当我运行以下代码时,只有8个通过。请注意,我使用了多个表,但是其中一些表每个联系人有多个行,有些表没有行,而有些表没有同一个表中的其他行。
SELECT
`Contact`.`firstName`,
`Contact`.`lastName`,
`ssn`.`ssn`,
`Contact`.`country`,
`Allergies`.`allergy`,
`Allergies`.`allergyType`,
`Allergies_Contact`.`allergyNotes`,
`CurrentPrescriptions`.`prescriptionName`,
`CurrentPrescriptions`.`prescribedDate`,
`BloodType`.`bloodType`
FROM
`mher`.`Contact`,
`mher`.`Allergies_Contact`,
`mher`.`Allergies`,
`mher`.`ssn`,
`mher`.`CurrentPrescriptions`,
`mher`.`BloodType`
WHERE
`Contact`.`contactKey` = `Allergies_Contact`.`contactKey`
AND `Allergies`.`allergiesKey` = `Allergies_Contact`.`allergiesKey`
AND `ssn`.`contactKey` = `Contact`.`contactKey`
AND `CurrentPrescriptions`.`contactKey` = `Contact`.`contactKey`
AND `BloodType`.`contactKey` = `Contact`.`contactKey`;
答案 0 :(得分:1)
你可以放手一搏,我已经把它作为你不需要条目的表的左连接:
SELECT
`Contact`.`firstName`,
`Contact`.`lastName`,
`ssn`.`ssn`,
`Contact`.`country`,
`Allergies`.`allergy`,
`Allergies`.`allergyType`,
`Allergies_Contact`.`allergyNotes`,
`CurrentPrescriptions`.`prescriptionName`,
`CurrentPrescriptions`.`prescribedDate`,
`BloodType`.`bloodType`
FROM
`mher`.`Contact`
INNER JOIN `mher`.`ssn`
ON `ssn`.`contactKey` = `Contact`.`contactKey`
INNER JOIN `mher`.`BloodType`
ON `BloodType`.`contactKey` = `Contact`.`contactKey`
LEFT JOIN `mher`.`Allergies_Contact`
ON `Contact`.`contactKey` = `Allergies_Contact`.`contactKey`
LEFT JOIN `mher`.`Allergies`
ON `Allergies`.`allergiesKey` = `Allergies_Contact`.`allergiesKey`
LEFT JOIN `mher`.`CurrentPrescriptions`
ON `CurrentPrescriptions`.`contactKey` = `Contact`.`contactKey`
;
答案 1 :(得分:0)
或 - 我的思想/眼睛,更具可读性......
SELECT c.firstName
, c.lastName
, ssn.ssn
, c.country
, a.allergy
, a.allergyType,
, ac.allergyNotes
, pc.prescriptionName
, pc.prescribedDate
, bc.bloodType
FROM Contact c
LEFT
JOIN Allergies_Contact ac
ON ac.contactKey = c.contactKey
LEFT
JOIN Allergies a
ON a.allergiesKey = ac.allergiesKey
JOIN ssn
ON ssn.contactKey = c.contactKey
LEFT
JOIN CurrentPrescriptions
ON pc.contactKey = c.contactKey
JOIN BloodType
AND bc.contactKey = c.contactKey;