我遇到SQL查询问题。我想将以下2个查询加入到一个查询中。
此查询应返回0,这是我期望的
SELECT COUNT(*) FROM table3 INNER JOIN table1 ON
table3.id = table1.id
WHERE table3.somefield = '0' AND table1.field1 = '1' AND table1.field2 = 'something') AS counts
此查询应返回2,这是我期望的
SELECT COUNT(*) FROM table3 INNER JOIN table2 ON
table3.id = table2.id
WHERE table3.somefield = '0' AND table2.field1 = '1' AND table2.field2 = 'something') AS counts
我合并了查询并将条件移到了JOIN但这会导致查询计数太多行
SELECT COUNT(*) FROM table3
LEFT JOIN table1 ON
table3.id = table1.id AND (table1.field1 = '1' AND table1.field2 = 'something')
LEFT JOIN table2 ON
table3.id = table2.id AND (table2.field1 = '1' AND table2.field2 = 'something')
WHERE table3.somefield = '0'
我期望的是查询的第一部分,它应该返回0,第二部分应该是2,但输出的是148,它必须与JOIN中的AND条件有关。
这里出了什么问题?
答案 0 :(得分:0)
在这里找到我的答案
mysql left join returns unexpected amount of rows
SELECT
(SELECT COUNT(*) FROM table3 INNER JOIN table1 ON
table3.id = table1.id
WHERE table3.somefield = '0' AND table1.field1 = '1' AND table1.field2 = 'something') +
(SELECT COUNT(*) FROM table3 INNER JOIN table2 ON
table3.id = table2.id
WHERE table3.somefield = '0' AND table2.field1 = '1' AND table2.field2 = 'something') AS countA,
(SELECT COUNT(*) FROM table3 INNER JOIN table1 ON
table3.id = table1.id
WHERE table3.somefield = '1' AND table1.field1 = '1' AND table1.field2 = 'something') +
(SELECT COUNT(*) FROM table3 INNER JOIN table2 ON
table3.id = table2.id
WHERE table3.somefield = '1' AND table2.field1 = '1' AND table2.field2 = 'something') AS countB
答案 1 :(得分:0)
正在进行的是您的个人查询使用INNER JOIN,而您的合并查询使用LEFT JOIN。
您可以通过在table2上使用INNER JOIN并在table1上使用LEFT JOIN来修复它:
SELECT * FROM table3
INNER JOIN table2 ON
table3.id = table2.id and table2.field1 = '1' AND table2.field2 = 'something'
LEFT JOIN table1 ON
table3.id = table1.id and table1.field1 = '1' AND table1.field2 = 'something'
WHERE table3.somefield = '0';
但这要求您在查询运行之前了解一些有关数据的信息(换句话说,它要求您已经知道table2有匹配而table1没有)。这不是一个好主意。
最好只获取COUNTs的SUM:
SELECT SUM(c) as totalCount
FROM (
SELECT COUNT(*) as c FROM table3 INNER JOIN table1 ON
table3.id = table1.id
WHERE table3.somefield = '0' AND table1.field1 = '1' AND table1.field2 = 'something'
UNION ALL
SELECT COUNT(*) as c FROM table3 INNER JOIN table2 ON
table3.id = table2.id
WHERE table3.somefield = '0' AND table2.field1 = '1' AND table2.field2 = 'something'
) bothCounts;