Retain ordering from IN subquery

送分小仙女□ 提交于 2019-12-06 13:03:46

I would use a join here instead of a subquery.

SELECT p.*
    FROM projects p
        INNER JOIN votes v
            ON p.id = v.project
    WHERE v.uid = x
    ORDER BY v.timestamp DESC;

try with ORDER BY FIELD - something like:

SELECT * FROM projects WHERE id IN(SELECT project FROM votes WHERE uid=x ORDER BY timestamp DESC) ORDER BY FIELD(id, (SELECT project FROM votes WHERE uid=x ORDER BY timestamp DESC) );

DISTINCT is not necessary because even though the IN() subquery may return duplicates, the outer query is merely looking for matching values among those, not 1:1 relationships. This is different than JOIN behavior, where you would likely end up with duplicate rows.

It's similar to saying you have an array [1,2,2,4,5,5] and asking which of the values from a different array [1,2,5,6] occur anywhere in the first array. The answer is always [1,2,5]. Hopefully this illustration isn't more confusing. I'll edit it as I think of ways to improve it.

Previous answers supply the correct ORDER BY.

You can rewrite this as a join:

SELECT DISTINCT projects.* FROM projects 
   JOIN votes ON projects.id = votes.project             
   ORDER BY timestamp DESC
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!