mysql order by multiple columns different directions - php

I have table.
Table structure is
And now I run the query
SELECT * FROM `studentregistrations`
ORDER BY `studentregistrations`.`studentID` DESC, `studentregistrations`.`studentName`
And the result I am getting is
I want an explanation how it is working. Because I am confusing that it should give result like studentID is in descending order and studentName is in ascending order.
I checked below answer but not getting any proper explanations
mysql query order by multiple items
PHP MySQL Order by Two Columns

I think your expectations are that the columns are sorted independently, so that all student names are in alphabetic order and all student ids are in descending order, independently on the names. If that would happen, you would get results where a student id is next to the wrong name, so fortunately that doesn't happen.
Instead, it sorts by the first column first and then by the next column. The secondary sort only applies to groups that have the same value in the first column.
So if you would have 10 students with the same ID, then for that ID their names would be alphabetically sorted.
But since the ID is unique, the secondary sorting is useless.
It would be useful, for example, to use
ORDER BY UniversityId, StudentName
That way, you would have a list where all students of the same university are grouped together, and within these groups they are sorted alphabetically by name.

When you sort using multiple columns, the order of the second column only influences the order when two or more values are equal in the first column. If all values in the first column are unique, the other order columns do not matter.

Your query first orders by student id, and then following that, orders any 'ties' by student name.
It's impossible to have both of your order by's honoured in full, because then there would be row/column mismatches.

Related

How to retrieve count values as multiple columns using group by in single query in MySQL?

I am writing a complex MySQL query. My actual query is more complex than I mentioned below.
I have a table named example and columns are id, name, option_1, option_2 . Of course id column is PK . I want to retrieve like this:
SELECT `id`,`name`,count(`option_1`),count(`option_2`)
My problem is I want to use "GROUP BY `id`" for count(`option_1`) and "GROUP BY `name`" for count(`option_2`) respectively. Now I have to break down it into multiple code in my php code.
How can I achieve what I want in a single query?
What you're asking for doesn't make a ton of sense. You want option 1 grouped by id and option 2 grouped by name, and you want to show all four columns in one result set.
First of all, if id is a primary key, then the count will just be the number of rows in the table since there will be no duplicate ids.
Second, even if id wasn't a primary key, and there were duplicate values, the grouping is different, so the counts represented in your result set would be grouped incorrectly.
Given that id is a primary key, perhaps your intention is actually to get a total count of the rows in the table. Perhaps this query would suit your needs?
SELECT
name,
COUNT(option_2) AS options
FROM
example
GROUP BY
name
UNION ALL
SELECT
'Total' AS name,
COUNT(*) AS options
FROM
example
This should get you a count of all the option_2 values, grouped by name, with the final row having a name of 'Total' and the count being the total number of rows in the table.
Aside from that, I'm not sure you're going to find the answer you're looking for due to the problems you would encounter matching up groupings.

PHP- Taking the Largest value from Mysql column of Unique ID

My current projects consist of Registration of families of different areas in a City. i want to Generate a Unique ID to each families in which i need this ID for another part of this project.Each area in the city have already a unique number eg: 855, 856, 857,etc
So my plan is to generate unique Family ID by combining unique number already have + text "FM"+ number (1,2,3....) and store this uid to DB along with family details.
For eg (Area-855): 855FM1, 855FM2, 855FM3....
if the last registered family uid is 855FM40 , then next family uid must be 855FM41. so i want to fetch the largest value from uid field. in above eg:, largest is 855FM41. how i do this. ?
i have simple logic that fetch all uid, then split it after "FM". then find largest ,etc
How i solve this problem.? is there any simple way other than this.?
Using ORDER command you can sort your data by ordering of one column ascending or descending.
so first we order FamilyID column descending (in sql we use DESC) and then we get the first row which has biggest FamilyID value using "LIMIT 0,1" command
Try this:
SELECT * FROM families ORDER BY FamilyID DESC LIMIT 0, 1
You should use two columns instead of one. For example this:
FamilyID
--------
855FM1
855FM2
Should be stored as:
CityID FMNumber
------ --------
855 1
855 2
This way the data should be easier to manage and less redundant. And yes, it is possible to define primary or unique keys over multiple columns.

Is there anyway to tell which fields are grouped fields in a MySQL result (PHP)

I have some PHP code that will run user-generated SQL on a MySQL table. The query possibilities are limited, but could be, for example
SELECT City, Country, count(*) FROM Table ... GROUP BY City, Country
or
SELECT count(*) AS Count, Role, Country FROM Table ... GROUP BY Role, Country
or
SELECT count(*), TicketType, City, SUM(Quantity) AS 'Total Quantity' FROM Table ... GROUP BY TicketType, City
and so on.
When presenting the results of the query, I want to take one type of action if the column is an grouped field (e.g. COUNT or SUM or AVG etc.)
Other than parsing the query, is there any way to determine which fields are grouped fields from the result set? I am using mysqli and PHP
it is simple I guess, the only fields you can select in SELECT clause are the fields that are either grouped in Group By clause or grouped by aggregated functions.
So when you use
SELECT City, Country, count(*) FROM Table ... GROUP BY City, Country
your result set will have multiple rows each with three columns:city,country,count(*). city and country are the fields which are grouped by.
Generally the answer is no.
What you receive from the db are field names and values. Without parsing the original query you can't be sure which fields are aggregations and which are not.
Probably in your case there can be constraints you can use. For example:
If numbers can be only generated fields you can check the contents of the result. (Of course this is very unstable.)
Maybe you can use the field's name as a hint. Maybe it contains something related to aggregations. (sum, count, total,...)
But probably to best/most stable way to handle your problem to get more control around the query generation, and set explicit constraints you need or save the details you need later.
Maybe you can try to use this function: http://www.php.net/manual/en/pdostatement.getcolumnmeta.php
But I don't think it will be satisfying.

How do I retrieve data with MySQL such that I won't be getting duplicate values in a single column?

I am currently working on a school system where we have a parent course and a child course (meta_courses in Moodle).
So, we have a table mdl_course_meta and it has 3 fields. Id, parent_course and child_course.
My problem is that a parent course can have many child courses so that means, for example, a parent_course = 50 can appear two times in the table which means it has 2 child courses. I just want to be able to find all the parent courses without it returning the same value twice or more times. I'm currently using this query right now which obviously doesn't do what I want:
$q = "SELECT * FROM mdl_course_meta";
I am working with PHP as well by the way.
Thanks a lot.
SELECT DISTINCT parent_course from mdl_course_meta
That should do it if you just want the course names. One thing to keep in mind, if you want other fields this is not going to work the way you want it to(how would it know which record to choose if there are multiple records with the same parent_course and you only want one).
This approach can only be used if you only want to return the parent_courses without duplicates.
DISTINCT helps to eliminate duplicates. If a query returns a result that contains duplicate rows, you can remove duplicates to produce a result set in which every row is unique. To do this, include the keyword DISTINCT after SELECT and before the output column list.
$q = "SELECT DISTINCT parent_course FROM mdl_course_meta";
If you don't want duplicate values in a single column, use GROUP BY parent_course.
In this way you are free to select any column.
If you only want distinct values for a particular column column, then you can use GROUP BY:
SELECT *
FROM mdl_course_meta
GROUP BY parent_course
The values in the other columns will be arbitrary. This will work in MySQL 5.x.
MySQL 4.x won't let you be arbitrary, so you can't mix aggregate and non-aggregate columns. Instead, you'd have to do something like this, which gets a bit complicated:
SELECT MAX(col1), MAX(col2), parent_course, MAX(col4), ...
FROM mdl_course_meta
GROUP BY parent_course
This way, the values aren't arbitrary. You've specified the ones you want.

finding the number of 1's in my table in order

I have a table of customers with a 1 recorded against their customerid on different dates.
I would like to find the sum of the 1's recorded in descending order. I'm using MySQL and php
Thanks
My guess is that you want the sum of records marked with 1 per customer and sort that result in descending order? If so, the following should do the trick :
select cust.id, sum(cone.one) as number_ones
from customers as cust
inner join customer_ones as cone on cone.id=cust.id
group by cust.id
order by number_ones desc
This is assuming that 'one' is the column containing ones (and only contains 0 or 1 - otherwise you will have to add WHERE cone.one = 1), customers is your customer table and customer_ones is the table containing your customer data.
As i get you right, this is simple sql request what u need:
SELECT COUNT(id) as total from customers
Just make in php:
$sql="SELECT COUNT(id) from customers";
$query=mysql_query($sql) or die(mysql_error());
$res=mysql_fetch_assoc($query);
$summ=$res['total']; //<- Your summ (i.e. quantity of rows in table)
Btw, you can use mysql_num_rows instead.
Or explain please more accurately what output you need. To make sorting by date or any other dependency you will need to make other request using WHERE clause and date comparison.

Categories