我有一个MySQL
语句,用于查询联系人表。当它们被加载到我的DataGrid
中时,同一个联系人有多个副本(表中只有1个)。
这让我相信我的MySQL
陈述有问题。这是我到目前为止所拥有的;
myQuery.CommandText = @"SELECT contacts.contactID, contacts.companyID,
companies.name, contacts.donestatus, employees.name,
people.ID, people.firstname, people.lastname,
contacts.contractID, contacts.date, contacts.time,
presets.presettext, contacts.madeby, contacts.description
FROM contacts
LEFT OUTER JOIN companies ON contacts.companyID = companies.ID
LEFT OUTER JOIN employees ON contacts.employeeID = employees.ID
LEFT OUTER JOIN people ON contacts.personID = people.ID
JOIN presets ON contacts.type = presets.presetIDFoxPro
WHERE contacts.companyid = @CompanyID
AND presets.presetreferencefoxpro = 8
ORDER BY contacts.date DESC";
我检查了方法,它肯定只调用一次,所以对我来说它必须是声明。多个JOINS
是否会为每个成功的Contact
加载JOIN
?
答案 0 :(得分:0)
在这种情况下,它取决于您想要出现的内容。如果联系人可以拥有多个相关公司,员工或人员,那么您将使用当前SQL将其中的每个组合带回记录。例如,如果一个联系人有2个,那么8行(即2 x 2 x 2)会回来进行该联系。
如果您希望每个联系人在一行上显示所有详细信息,那么您可以使用子查询来获取每个联系人的所有联接详细信息,然后将其结果与联系人表联系起来。
举个简单的例子: -
SELECT contacts.contactID, contacts.companyID,
sub_companies.name, contacts.donestatus, sub_employees.name,
sub_people.all_id, sub_people.all_firstname, sub_people.all_lastname,
contacts.contractID, contacts.date, contacts.time,
presets.presettext, contacts.madeby, contacts.description
FROM contacts
INNER JOIN presets ON contacts.type = presets.presetIDFoxPro
LEFT OUTER JOIN
(
SELECT ID, GROUP_CONCAT(name)
FROM companies
GROUP BY ID
) sub_companies ON contacts.companyID = sub_companies.ID
LEFT OUTER JOIN
(
SELECT ID, GROUP_CONCAT(name)
FROM employees
GROUP BY ID
) sub_employees ON contacts.employeeID = sub_employees.ID
LEFT OUTER JOIN
(
SELECT ID, GROUP_CONCAT(ID) AS all_id, GROUP_CONCAT(firstname) AS all_firstname, GROUP_CONCAT(lastname) AS all_lastname
FROM people
GROUP BY ID
) sub_people ON contacts.personID = sub_people.ID
WHERE contacts.companyid = @CompanyID
AND presets.presetreferencefoxpro = 8
ORDER BY contacts.date DESC