简体   繁体   English

从同一个表中获取父级行; 根据行按不同条件排序

[英]Getting child-parent rows from same table; sort by different criteria based on row

I am using MySQL. 我正在使用MySQL。 I already have a query that does one important part of this: 我已经有一个查询,它执行此操作的一个重要部分:

Get the newest parent row from the table comments , and for each parent comment, get the child's comments and sort by the oldest. 从表comments获取最新的父行,并为每个父注释获取子项的注释并按最旧的排序。 Note: There is a column called parent_id . 注意:有一列称为parent_id All parent's are 0 , all children, of course, are greater than 0 . 所有父母的全都为0 ,所有孩子当然都大于0 Also, it is sorting on a column called create_date 此外,它还在名为create_date的列上排序

This was very doable because the parent and children are both being sorted on create_date , (even if one was ASC and one was DESC). 这是非常可行的,因为父母和孩子都在create_date上进行了排序(即使一个是ASC,一个是DESC)。

Now I want to add the option for the users to sort by "top" comments, not just the "newest" as I am doing here: 现在,我想为用户添加按“热门”评论排序的选项,而不仅仅是我在这里所做的“最新”评论:

SELECT * FROM (
SELECT c1.*, c1.create_date ac, c1.create_date ap FROM comments c1 
WHERE parent_id = 0 AND c1.profile_id = 582 
UNION 
SELECT c2.*, c2.create_date ac, p.create_date ap FROM comments c2 
JOIN comments p ON c2.parent_id = p.id 
WHERE c2.profile_id = 582 
) c
ORDER BY c.ap DESC, c.ac ASC;

So the caveat is now I want to sort the parents by a column called votes (DESC) and the children (or comment replies) the same as above: create_date ASC . 因此,需要注意的是,我现在想按称为votes (DESC)的一列对父级进行排序,而子级(或评论答复)与上面相同: create_date ASC

I have tried sub-querys, ORDER BY 's with CASE statements and more. 我尝试了子查询,带有CASE语句的ORDER BY和更多子查询。 What do I need to do for this one sorting modification? 我需要对这一项排序进行修改吗?

Note: Performance is nice, but not the hugest issue here. 注意:性能不错,但这里不是最大的问题。 Also, I know I can do this with code + looping though an outer query -- but I rather not go that route if possible. 另外,我知道我可以通过外部查询通过代码+循环来做到这一点-但我宁愿不走那条路。

SELECT * FROM 
(
     SELECT c1.*, c1.vote_count totals, c1.parent_id pa_id, c1.id p_id, c1.create_date ac, c1.create_date ap FROM comments c1 
     WHERE parent_id = 0 AND c1.profile_id = 582 
     UNION 
     SELECT c2.*, p.vote_count totals, p.parent_id pa_id, p.id p_id, c2.create_date ac, p.create_date ap FROM comments c2 
     JOIN comments p ON c2.parent_id = p.id 
     WHERE c2.profile_id = 582 
) c
ORDER BY c.totals DESC, 
CASE
  WHEN c.pa_id = 0 THEN c.p_id
  ELSE c.parent_id
END ASC,
c.ac ASC

I just make a new alias column called totals that basically assigns the parent's vote count to the child so they will sort together. 我只是创建了一个名为totals的新别totals ,该列基本上将父母的投票计数分配给孩子,以便他们可以一起排序。

Edit: I also had to add the parent comment's id and parent id for sorting purposes which is used in the new CASE statement in the ORDER BY 编辑:我还必须添加父注释的ID和父ID以便进行排序,这在ORDER BY中的新CASE语句中使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM