使用SELECT DISTINCT()和ORDER BY时遇到问题... 这是我的SQL:
SELECT DISTINCT(t2)
FROM Table1 t1
JOIN Table2 t2 ON t1.t2 = t2.id
JOIN Table3 t3 ON t1.t3 = t3.id
JOIN Table4 t4 ON t2.t4 = t4.id
JOIN Table5 t5 ON t2.t5 = t5.id
JOIN Table6 t6 ON t2.t6 = t6.id
ORDER BY t4.date DESC
但这是错的......你有什么想法吗?
提前致谢! =)
答案 0 :(得分:2)
在SELECT DISTINCT
查询中,您只能按SELECT
中的列进行排序。毕竟,date
的值应该用于排序?
好的,我猜可以。 。 。最大值。所以,使用聚合:
SELECT t2
FROM Table1 t1 JOIN
Table2 t2 ON t1.t2 = t2.id JOIN
Table3 t3 ON t1.t3 = t3.id JOIN
Table4 t4 ON t2.t4 = t4.id JOIN
Table5 t5 ON t2.t5 = t5.id JOIn
Table6 t6 ON t2.t6 = t6.id
GROUP BY t2
ORDER BY MAX(t4.date) DESC;
答案 1 :(得分:0)
你的t2只是你桌子的别名,不能这样做:
应该是这样的:
SELECT DISTINCT t2.*,t3.*,t4.*
FROM Table1 t1
JOIN Table2 t2 ON t1.id = t2.id
JOIN Table3 t3 ON t1.id = t3.id
JOIN Table4 t4 ON t2.id = t4.id
JOIN Table5 t5 ON t2.id = t5.id
JOIN Table6 t6 ON t2.id = t6.id
ORDER BY t4.date DESC
如果你使用*,你必须小心使用相同的列名,因为它会返回一个含糊不清的错误..你可以简单地喜欢t3.column1等等。
答案 2 :(得分:0)
只需进行子查询
SELECT * FROM
(
SELECT DISTINCT *
FROM Table1 t1
JOIN Table2 t2 ON t1.t2 = t2.id
JOIN Table3 t3 ON t1.t3 = t3.id
JOIN Table4 t4 ON t2.t4 = t4.id
JOIN Table5 t5 ON t2.t5 = t5.id
JOIN Table6 t6 ON t2.t6 = t6.id
)
ORDER BY t4.date DESC