开发者

MySQL, how to display descending age of children and children of the same age listed alphabetically?

开发者 https://www.devze.com 2023-03-19 21:48 出处:网络
I am having difficultiesin the order by result. It gives me all the info I need but the children with the same age don\'t show ordered by surname alphabetically.

I am having difficulties in the order by result. It gives me all the info I need but the children with the same age don't show ordered by surname alphabetically.

I need a list showing the name and age (in years) of each child on the day that the query is run. The list should be sorted in descending order of age (i.e. oldest children first) with children of the same age listed alphabetically by surname, first name.

Here is my syntax

SELECT *, TIMESTAMPDIFF(YEAR, child_dob, CURRENT_TIMESTAMP) AS age 
FROM Children 
ORDER BY child_dob, child_sname, child_fname;

I'm really stuck, hope someone can开发者_StackOverflow社区 shed a light please.

Thanks


You forgot two things:

  1. You need to order by age, not by date of birth--unless you really only want to order by last name for children born on the exact same day.
  2. To show oldest children first, you need to order by age with the DESC keyword.

Here's the proper query:

SELECT *, TIMESTAMPDIFF(YEAR, child_dob, CURRENT_TIMESTAMP) AS age 
FROM Children 
ORDER BY age DESC, child_sname, child_fname;


You are ordering by child_dob, which is presumably a date field, instead of by age (which is the child's age in years).

ORDER BY age DESC, child_sname, child_fname


SELECT *, TIMESTAMPDIFF(YEAR, child_dob, CURRENT_TIMESTAMP) AS age 
FROM Children 
ORDER BY age, child_sname, child_fname;
0

精彩评论

暂无评论...
验证码 换一张
取 消