SELECT DISTINCT ID FROM (SELECT * FROM tbl1 UNION
SELECT * FROM tbl2 UNION
SELECT * FROM tbl3 UNION
SELECT * FROM tbl4 ORDER BY total_hits DESC) AS sumtbl LIMIT 50;
此查询工作正常,并选择按total_hits DESC
排序的唯一ID,问题是如何返回total_hits
列也具有Id的唯一性?
答案 0 :(得分:2)
SELECT ID, SUM(total_hits)
FROM (
SELECT * FROM tbl1 UNION
SELECT * FROM tbl2 UNION
SELECT * FROM tbl3 UNION
SELECT * FROM tbl4
) AS sumtbl
GROUP BY ID
ORDER BY SUM(total_hits) DESC
LIMIT 50;
答案 1 :(得分:0)
如果你想要所有表中的所有id的total_hits FROM,你需要做一个sum / group by。不确定这是不是你问的问题,因为问题很模糊......
SELECT DISTINCT id, sum(total_hits) total_hits
FROM (SELECT * FROM tbl1 UNION
SELECT * FROM tbl2 UNION
SELECT * FROM tbl3 UNION
SELECT * FROM tbl4) AS sumtbl
GROUP BY id
ORDER BY total_hits DESC
LIMIT 50
此外,不要使用select *,因为这是不好的做法,尤其是如果您要将列添加到其中一个表而不是其他表,则整个查询将会中断。
答案 2 :(得分:-1)
<强>更新强>
在你的情况下你可以做到
SELECT ID, MAX(total_hits) as max_hits
FROM (
SELECT * FROM tbl1 UNION
SELECT * FROM tbl2 UNION
SELECT * FROM tbl3 UNION
SELECT * FROM tbl4
)sumtbl
GROUP BY ID
ORDER BY max_hits DESC
LIMIT 50
注意:在派生查询中不需要ORDER BY
,它会转到上面的
另外,如果你是的话会更好
SELECT id, total_hits
等,而不是从派生查询中的表中选择所有字段。
FROM tbl1
UNION ALL
SELECT id, total_hits FROM tbl2