我正在多个JOIN表上执行查询:
SELECT TableA.*,
TableB.Data as Data_B,
TableC.Data as Data_C,
TableD.Data as Data_D,
TableE.*
FROM TableA JOIN TableB ON TableB.ID = TableA.ID
JOIN TableC ON TableC.ID = TableB.ID
JOIN TableD ON TableD.ID = TableC.ID
JOIN TableE ON TableE.ID = TableA.ID
WHERE DataToFind = '$SubmittedData'
它运行良好,但由于TableA是主表,而TableE是一个通过密钥ID与TableA关联的多子表,当我在TableA字段上执行搜索时,我得到TableA的多个行,与TableE记录一样多。 / p>
由于我只是在我执行搜索后想要DISTINCT,我的理想查询应该是:
SELECT DISTINCT ID FROM
(
SELECT TableA.*,
TableB.Data as Data_B,
TableC.Data as Data_C,
TableD.Data as Data_D,
TableE.*
FROM TableA JOIN TableB ON TableB.ID = TableA.ID
JOIN TableC ON TableC.ID = TableB.ID
JOIN TableD ON TableD.ID = TableC.ID
JOIN TableE ON TableE.ID = TableA.ID
WHERE DataToFind = '$SubmittedData'
)
WHERE ID IS NOT NULL
但由于我收到“意外令牌”和其他语法错误,因此无效。
你能帮我找一下如何正确格式化吗?
P.S。我不在乎是否丢失了一些TableE记录,因为我可以在需要时使用找到的ID恢复它们。
答案 0 :(得分:1)
如果你想要不同的id,那么把它们全部放在一个select语句中:
SELECT DISTINCT TableA.ID
FROM TableA JOIN
TableB
ON TableB.ID = TableA.ID JOIN
TableC
ON TableC.ID = TableB.ID JOIN
TableD
ON TableD.ID = TableC.ID JOIN
TableE
ON TableE.ID = TableA.ID
WHERE DataToFind = '$SubmittedData';
您的版本存在问题,因为子查询中有两列名为ID
。这将产生另一个错误。
答案 1 :(得分:0)
您的查询没问题。它只是缺少子查询的表别名,如
SELECT DISTINCT ID FROM
(
SELECT tableA.*,
TableB.Data as Data_B,
TableC.Data as Data_C,
TableD.Data as Data_D
TableE.*
FROM tableA JOIN tableB ON tableB.ID = tableA.ID
JOIN tableC ON tableC.ID = tableB.ID
JOIN tableD ON tableD.ID = tableC.ID
JOIN tableE ON tableE.ID = tableA.ID
WHERE DataToFound = '$SubmittedData'
) xxx <-- missing
WHERE ProcedureID IS NOT NULL