目前,我正在尝试通过查询名为 Payslip 的表格中的 Start_Periods 列表进行查询。这只是一个简单的查询,我在测试之前将其变成复杂的东西。但是在这个非常简单的层面上,mySql Engine如何显示我的数据似乎有些不对。
我当前的查询是
QTextDocument doc;
doc.setHtml(html);
qDebug() << "Success\n\n" << doc.toPlainText()
哪个输出:
SELECT a.SPERIOD
FROM Payslip a
LEFT JOIN Earndetl b ON a.SPERIOD = b.SPERIOD
LEFT JOIN Ded_detl c ON a.SPERIOD = c.SPERIOD
WHERE MONTH(a.SPERIOD) = 1
AND MONTH(b.SPERIOD) = 1
AND MONTH(c.SPERIOD) = 1
GROUP BY a.SPERIOD;
以下查询:
SPERIOD
2015-01-01
2015-01-16
输出:
SELECT SPERIOD FROM Payslip WHERE MONTH(SPERIOD) = 1 GROUP BY SPERIOD;
由于我只使用左连接到 EarnDetl 和Ded_detl,无论两个表中是否存在相同的 SPERIOD ,这应该不是问题吧?或者我的查询有什么问题,我在过去一小时内没有看到?
答案 0 :(得分:4)
当LEFT JOIN
时,将右侧表的条件放在ON
子句中以获得真正的左连接行为! (在WHERE
中,您获得常规的内部联接结果):
SELECT a.SPERIOD
FROM Payslip a
LEFT JOIN Earndetl b ON a.SPERIOD = b.SPERIOD AND MONTH(b.SPERIOD) = 1
LEFT JOIN Ded_detl c ON a.SPERIOD = c.SPERIOD AND MONTH(c.SPERIOD) = 1
WHERE MONTH(a.SPERIOD) = 1
GROUP BY a.SPERIOD;
如果您不打算选择除.SPERIOD之外的任何其他内容,则可以删除GROUP BY
,而不是SELECT DISTINCT
。
答案 1 :(得分:0)
思想id用with
子句来做这件事只是为了一点乐趣。
WITH
A as (
SELECT * FROM Payslip WHERE MONTH(SPERIOD) = 1
),
B as (
SELECT * FROM Earndetl WHERE MONTH(SPERIOD) = 1
),
C as (
SELECT * FROM Ded_detl WHERE MONTH(SPERIOD) = 1
)
SELECT a.SPERIOD
FROM A
LEFT JOIN B ON A.SPERIOD = B.SPERIOD
LEFT JOIN C ON A.SPERIOD = C.SPERIOD
GROUP BY a.SPERIOD;