我想从表中选择包含50个最常用列值的所有行。我尝试使用这样的连接,但似乎我选择LEFT JOIN是错误的。声明的内部部分似乎很好。我的陈述中应该改变什么?
SELECT col1, col2
FROM tbl as t1
LEFT JOIN (
SELECT id
FROM tbl
WHERE id > 123
AND id < 987654
GROUP BY col1
ORDER BY COUNT(id) DESC
LIMIT 50
) AS t2
ON t1.id = t2.id
答案 0 :(得分:0)
您是否尝试使用IN运算符作为WHERE子句的一部分而不是JOIN?
例如......
SELECT col1, col2
FROM tbl as t1
WHERE t1.id IN (
SELECT id
FROM tbl
WHERE id > 123
AND id < 987654
GROUP BY col1
ORDER BY COUNT(id) DESC
LIMIT 50
)
答案 1 :(得分:0)
如果你的子查询是正确的,右连接应该有效,返回任何匹配的t1到t2的行(而不是t1的所有行和匹配的t2&#39; s或null):
SELECT col1, col2
FROM tbl as t1
RIGHT JOIN (
SELECT id
FROM tbl
WHERE id > 123
AND id < 987654
GROUP BY col1
ORDER BY COUNT(id) DESC
LIMIT 50
) AS t2
ON t1.id = t2.id
答案 2 :(得分:0)
我意识到我的查询没问题,我只想加入col1,而不是id:)
SELECT col1, col2
FROM tbl as t1
LEFT JOIN (
SELECT col1
FROM tbl
WHERE id > 123
AND id < 987654
GROUP BY col1
ORDER BY COUNT(id) DESC
LIMIT 50
) AS t2
ON t1.col1 = t2.col1