php, sql selection - php

I have a stupid question, I have this table :
id_product name value
1 price 10-20
1 type computer
2 price 20-30
3 price 100-200
and I want to select from this table GROUP BY id_product and ORDER BY value WHERE name='price'
how can i do this?
Thanks a lot

select * from table_name WHERE name='price'
GROUP BY id_product
ORDER BY value
In PHP
mysql_query("select * from table_name WHERE name='price'
GROUP BY id_product
ORDER BY value") or die(mysql_error());

SELECT *
FROM table_name
WHERE name = 'price'
GROUP BY id_product
ORDER BY value
You can see this for MySQL Select syntax

select * from table_name where name='price' Group By id_product ORDER By value;

right off the top of my head...
does it work?
SELECT * FROM `table` WHERE `table`.`name`='price' GROUP BY `table`.id_product ORDER BY `table`.`value` ASC

It depends on how you want to group items with the same id: which one do you want to be shown? In theory GROUP BY shouldn't be used with SELECT * (it does not work with non mysql databases) and should be associated with aggregate funcions such as COUNT(), MAX(), etc.
You might just need SELECT DISTINCT instead of GROUP BY.

This will select distinct id_product from table_name and order by value where name is "price". I think this will give the outcome you're after.
SELECT DISTINCT id_product
FROM table_name
ORDER BY (
SELECT t.value FROM table_name t
WHERE t.name='price'
AND t.id_product = table_name.id_product
)

Related

Explain a MySQLi query that displays top 3 sold cars

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

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

Order by in mysql without asc and desc

I have a table 'book_history' with a field 'status'
So there are three values for the field 'status' => 0,1,2
Now i want to query it in orderby - I know order by asc and order by desc is there.
But how i really want is
select * from book_history order by status 1,0,2
I checked with order by then also. But I was not able to make my query.
So the final output will be - first it should list the status=1, then status=0 and then status='2'
Any help.
Thanks,
Kimz
You can use FIELD() function
SELECT
*
FROM
book_history
ORDER BY FIELD(`status`, 1, 0, 2)
Use below query to force order in query:
select * from book_history
ORDER BY FIELD (status,1,0,2);
For more information if there is more values and you keep your values on top and rest values after that then you can use below query:
select * from book_history
ORDER BY FIELD (status,2,0,1) desc;
You can use ORDER BY FIELD:
SELECT * FROM book_history ORDER BY FIELD(status, 1,0,2)
Use a case expression to get an order key:
select *
from book_history
order by
case status
when 1 then 100 -- any small value would do here
when 0 then 200 -- any medium value would do here
when 2 then 300 -- any big value would do here
end;
Another alternative with UNION:
select * from book_history where status = 1
UNION
select * from book_history where status = 0
UNION
select * from book_history where status = 2

fetch column2 value corresponding to column1 maximum,minimum?

Is it possible to fetch column2 values for max(column1). help me. I got to find the date corresponding to the max(price) and min(price) in database.
$str="select MAX(psq_price),MIN(psq_price),AVG(psq_price) from crawl_archives where p_id=2570";
I found max , min values from this query.. Need to find the date column corresponding to the maximum price ..
try this
select date , MAX(psq_price),MIN(psq_price)
from mytable
group by date
try something like this:
select *
from <table> t
join (select max(price) as max_price
from <table>
group by <col1>
)a
on a.col1=t.col1
and a.max_price=t.price

Select on Mysql inverse order

i have a MySql table that consists of 2 basic things:
The id and a value.
To show that on my page, i need to select, for example, the last 100 rows on reversed order.
So imagine that someone is putting data on it:
Id, value
1, 10
2, 9
3, 21
4, 15
i need, to select the last "3" rows (LIMIT + ORDER Clause), but not like this: 4,3,2 but like this: 2,3,4.
I know how to do that on code, but maybe there is a simple solution for that on Mysql and i don`t know.
Thanks
My SQL Query is like this right now:
SELECT `Data`.`id`, `Data`.`log_id`, `Data`.`value`, `Data`.`created` FROM `control_panel`.`datas` AS `Data` WHERE `Data`.`id` > 1000 AND `Data`.`log_id` = (2) ORDER BY `Data`.`id` DESC LIMIT 100
You need to wrap the first ORDER BY in a subselect which will return a limited selection ordered in descending order, then you can order that result in the outer query in ascending order:
SELECT
a.*
FROM
(
SELECT id, value
FROM tbl
ORDER BY id DESC
LIMIT 3
) a
ORDER BY
a.id
One way to do this would be with a sub-select.
SELECT *
FROM (SELECT * FROM table_name ORDER BY id DESC LIMIT 3) tmp
ORDER BY id ASC
simply
SELECT t.*
(SELECT * FROM table_name
ORDER BY column_name DESC
LIMIT 0,3) t
ORDER BY t.column_name ASC
use DESC to descending order, ASC to increasing order

Categories