Explain a MySQLi query that displays top 3 sold cars - php

I found the following mysqli query on the internet. It displays top 3 sold cars
//create conection with mysql database.
$conn = mysqli_connect("localhost","root","","cars");
//query
$select = "SELECT ord.*, sum(amount) as amt from orders as ord GROUP BY id_car order by amt desc limit 0,3";
$data = mysqli_query($conn,$select);
This query works fine but I would like if anyone can explain me this first section of the query: SELECT ord.*,
It seems like "ord" refers to orders but is it the same as saying: SELECT * FROM orders??
See table in the screenshot image
orders table

In the query there is orders as ord this gives the orders table an 'alias' of the orders table, so ord.* means orders.*
It is a bit redundant in this query to be honest, mainly used if there are multiople tables in a query :)
For this query you can simply do:
$select = "SELECT *, sum(amount) as amt from orders GROUP BY id_car order by amt desc limit 0,3";

Let's break it down:
a) Select all fields from table named ord which will be defined in c)
SELECT ord.*,
b) Select sum of column amount and name it amt
sum(amount) as amt
c) Use table orders for the query and define an alias name ord for that table, see a)
from orders as ord

It is same as select * from tableName,it will fetch all columns from table.But alias Name is given for the table. Using alias Name is best practices for joining the multiple tables.
since you are using single table you can do this also.
SELECT *, sum(amount) as amt from orders as ord GROUP BY id_car order by amt desc limit 0,3

Related

retrieve results of 2 table using JOIN failed

I have 2 tables, names and phones I did this for the query
$result = mysqli_query($mysqli, "SELECT * FROM names ORDER BY fname ASC
RIGHT JOIN phones ON phones.id=names.phone_id"
);
I got $result as false. My names table has a column named phone_id and it's a PK of phones's id, like so
names
- phone_id (FK)
phones
- id (PK)
What's wrong with my sql above?
The syntax should go like this:
SELECT *
FROM names
RIGHT JOIN phones ON phones.id = names.phone_id
ORDER BY fname ASC
The ORDER BY had to be moved to the end.
Order by should be the last part of your query
SELECT *
FROM names n
RIGHT JOIN phones p ON p.id=n.phone_id
ORDER BY fname ASC
Start using alias names to make the query more readable
You should use ORDER BY as last clause of your query. Becasue order by i.e. sorting works at last after fetch.
SELECT *
FROM names as n
RIGHT JOIN phones as p ON p.id=n.phone_id
ORDER BY fname ASC
To see more abour ORDER BY you can check the manual link

Select most common value? [duplicate]

How can I find the most frequent value in a given column in an SQL table?
For example, for this table it should return two since it is the most frequent value:
one
two
two
three
SELECT
<column_name>,
COUNT(<column_name>) AS `value_occurrence`
FROM
<my_table>
GROUP BY
<column_name>
ORDER BY
`value_occurrence` DESC
LIMIT 1;
Replace <column_name> and <my_table>. Increase 1 if you want to see the N most common values of the column.
Try something like:
SELECT `column`
FROM `your_table`
GROUP BY `column`
ORDER BY COUNT(*) DESC
LIMIT 1;
Let us consider table name as tblperson and column name as city. I want to retrieve the most repeated city from the city column:
select city,count(*) as nor from tblperson
group by city
having count(*) =(select max(nor) from
(select city,count(*) as nor from tblperson group by city) tblperson)
Here nor is an alias name.
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
For use with SQL Server.
As there is no limit command support in that.
Yo can use the top 1 command to find the maximum occurring value in the particular column in this case (value)
SELECT top1
`value`,
COUNT(`value`) AS `value_occurrence`
FROM
`my_table`
GROUP BY
`value`
ORDER BY
`value_occurrence` DESC;
Assuming Table is 'SalesLT.Customer' and the Column you are trying to figure out is 'CompanyName' and AggCompanyName is an Alias.
Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;
If you can't use LIMIT or LIMIT is not an option for your query tool. You can use "ROWNUM" instead, but you will need a sub query:
SELECT FIELD_1, ALIAS1
FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1
FROM TABLENAME
GROUP BY FIELD_1
ORDER BY COUNT(FIELD_1) DESC)
WHERE ROWNUM = 1
If you have an ID column and you want to find most repetitive category from another column for each ID then you can use below query,
Table:
Query:
SELECT ID, CATEGORY, COUNT(*) AS FREQ
FROM TABLE
GROUP BY 1,2
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FREQ DESC) = 1;
Result:
Return all most frequent rows in case of tie
Find the most frequent value in mysql,display all in case of a tie gives two possible approaches:
Scalar subquery:
SELECT
"country",
COUNT(country) AS "cnt"
FROM "Sales"
GROUP BY "country"
HAVING
COUNT("country") = (
SELECT COUNT("country") AS "cnt"
FROM "Sales"
GROUP BY "country"
ORDER BY "cnt" DESC,
LIMIT 1
)
ORDER BY "country" ASC
With the RANK window function, available since MySQL 8+:
SELECT "country", "cnt"
FROM (
SELECT
"country",
COUNT("country") AS "cnt",
RANK() OVER (ORDER BY COUNT(*) DESC) "rnk"
FROM "Sales"
GROUP BY "country"
) AS "sub"
WHERE "rnk" = 1
ORDER BY "country" ASC
This method might save a second recount compared to the first one.
RANK works by ranking all rows, such that if two rows are at the top, both get rank 1. So it basically directly solves this type of use case.
RANK is also available on SQLite and PostgreSQL, I think it might be SQL standard, not sure.
In the above queries I also sorted by country to have more deterministic results.
Tested on SQLite 3.34.0, PostgreSQL 14.3, GitHub upstream.
Most frequent for each GROUP BY group
MySQL: MySQL SELECT most frequent by group
PostgreSQL:
Get most common value for each value of another column in SQL
https://dba.stackexchange.com/questions/193307/find-most-frequent-values-for-a-given-column
SQLite: SQL query for finding the most frequent value of a grouped by value
SELECT TOP 20 WITH TIES COUNT(Counted_Column) AS Count, OtherColumn1,
OtherColumn2, OtherColumn3, OtherColumn4
FROM Table_or_View_Name
WHERE
(Date_Column >= '01/01/2023') AND
(Date_Column <= '03/01/2023') AND
(Counted_Column = 'Desired_Text')
GROUP BY OtherColumn1, OtherColumn2, OtherColumn3, OtherColumn4
ORDER BY COUNT(Counted_Column) DESC
20 can be changed to any desired number
WITH TIES allows all ties in the count to be displayed
Date range used if date/time column exists and can be modified to search a date range as desired
Counted_Column 'Desired_Text' can be modified to only count certain entries in that column
Works in INSQL for my instance
One way I like to use is:
select *<given_column>*,COUNT(*<given_column>*)as VAR1 from Table_Name
group by *<given_column>*
order by VAR1 desc
limit 1

Searching and Counting Data in PHP

I want to search data based on month and year. Then, it will count the same id for Book_id.
I have problems to count the Book_id for monthly. This query will count for entire records including monthly, which is not the result I want.
$res2 = mysql_query( "SELECT DISTINCT Date_borrow, Book_name as nmBook, Book_id as b_id, count(Book_name) AS count
FROM transaksi
GROUP BY nmBook
HAVING count > 1
ORDER BY COUNT DESC ");
$rowss = mysql_fetch_array($res2);
Thanks for your help.
I am taking a shot at it not knowing you complete data model
SELECT DISTINCT Date_borrow, Book_name as nmBook, Book_id as b_id,
count(Book_name) AS count
FROM transaksi
GROUP BY nmBook
HAVING count > 1
ORDER BY COUNT DESC
Should be:
SELECT Date_borrow, Book_name as nmBook, Book_id as b_id,
count(Book_name) AS counter
FROM transaksi
GROUP BY Book_name,Date_borrow,book_id
HAVING count(Book_name) > 1
ORDER BY `counter` DESC;
DISTINCT and GROUP BY are mutually exclusive: Once you use GROUP BY, apply either a function on all the fields or add the fields in the GROUP BY.
HAVING COUNT(Book_name): COUNT needs a parameter, so book_name in this case since that is the same as in your SELECT statement.
Use of just created alias in ORDER BY: Test that. Could be that you need to use COUNT(book_name) there too.
Use of reserved word "COUNT" as alias: Avoid the use of any terms sounding like functions or code in table names, column names, function names etc. Invent your own naming standard which avoids this use of (possibly) reserved key words.

Search MySQL database, order results by COUNT

I have a database table 'sales_list'. In this is rows of sales records attributed to a users_sales_guild_id. I'd like to query the table and order results by the number of sales made by each user, highest to lowest.
I thought this query would do it, but alas no...
$total_query = "SELECT *, COUNT(users_sales_guild_id) AS users_sales_guild_id_count FROM sales_list WHERE sales_entry_date BETWEEN '2013-10-01 00:00:00' AND '2014-11-30 23:59:59' ORDER BY users_sales_guild_id_count DESC";
$total_rs = mysql_query($total_query) or trigger_error ("Query: $total_query\n<br>MySQL Error: " .#mysql_error()); // Run the query.
$num_rs = mysql_num_rows($total_rs);
This query returns 1 record. rather than a selection of records ordered by the number of sales by each user.
Your assistance is much welcomed.
count(*) will return one row unless there is a group by clause, so the query should be as
SELECT *,
COUNT(*) AS users_sales_guild_id_count
FROM sales_list
WHERE sales_entry_date BETWEEN '2013-10-01 00:00:00' AND '2014-11-30 23:59:59'
group by users_sales_guild_id
ORDER BY users_sales_guild_id_count DESC
UPDATE : Its better to select col1,col2 ..... instead of * while doing group by - Point raised by InoSHeo
check this link
http://sqlfiddle.com/#!2/1201d/6
check this link if you would like to get details based on username http://sqlfiddle.com/#!2/1201d/4 here i have used type instead you can use username

Using PHP to show the latest X rows in an Oracle table

I'm having a problem getting Oracle to return the latest X rows in a table (i.e. in this case it would be returning our newest orders).
$stid = oci_parse($conn, "
SELECT OrderNo, InvoiceNo
FROM Orders
WHERE ROWNUM <= 5
ORDER BY ROWNUM DESC
");
Reading this makes sense in that the highest row numbers should be first and it should show the first five. What am I doing wrong here?
You just need to encapsulate your query in a subquery and you should be fine:
SELECT *
FROM
(
SELECT OrderNo, InvoiceNo
FROM Orders
ORDER BY OrderNo, InvoiceNo DESC -- choose the correct sorting here
)
WHERE ROWNUM <= 5

Categories