Mysql - Order By in IN Clausole - php

I have a simple question.
I have to join multiple queries and most of them has ad IN clausole.
Unfortunally, MySQL doesn't allow ORDER BY in an UNION (only outside all unions) but I need a specific ordering that I can't get with an outside order by.
Question is:
If I have a IN clausole like
foo in ('newyork','boston','atlanta')
may I assume MySql's engine will order the resulting rows by IN position (so, first all the row with foo = 'newyork' then 'boston' etc...
Thanks.

No. It's nothing like that. You need to explicitly add an order by clause.
If you want to order your rows based on position in a set, you can use field function.
order by field(foo,'newyork','boston','atlanta')

Select *
from
(
Select * from Temp1
order by x
) Tbl1
UNION
Select *
from
(
Select * from Temp2
order by y
) Tbl2
Try this.

Related

query group by with order by

i need to create query with group by and order by, and i dont know how to do it.
query should return one record for the newest date for existing device_serial_number. enter image description here
so i would to get id 591 nad 592
solution can be in sql or the best way it will be in symfony, through query builder etc.
There are many ways to accomplish what you want.
First Way
The oldest way to select first, best, worst, whatever within a group is with a correlated subquery:
Select * from mytable outer
Where created_at = (
Select max(created_at)
from mytable inner
Where inner.device_serial_number = outer.device_serial_number
)
Second Way
Use a subselect to find earliest dates for all devices, them join back to the original table to filter:
Select a.*
From mytable a Inner Join
(Select device_serial_number, max(created_at) as latedate
From mytable b
Group By device_serial_number
) b
On a.device_serial_number=b.device_serial_number
And a.created_at=b.latedate
Third way
Use a window function to rank order all the dates and then pick the number one ranking.
Select * From (
Select *
, rank() Over (Partition By device_serial_number Order by created_at desc) as myrank
From mytable
)
Where myrank=1
Notice that while these 3 solutions use different aspects of SQL, they all have a common analytical approach. They are all two step processes whose first (inner) part involves finding the most recent created_at date for each device_serial_number and then reapplying that result back to the original table in the second (outer) part.

Using a Select query inside a select query?

I am trying to use a select query within another select query in the from clause.This is a mysql query.
SELECT invoiceNo, SUM(weight), COUNT(barcode), sum_total
FROM (SELECT * FROM `selected_items` WHERE date LIKE '07-Jan-2016' ORDER BY id DESC)
WHERE date LIKE '07-Jan-2016' GROUP BY invoiceNo;
This is how my database looks like.
How can I achieve something like this where I have a table which I order by id desc and use another select query on the result of this query.The above query gives me an error #1248 - Every derived table must have its own alias.Can anyone help I am new to programming.
I hope this will help you out .
SELECT invoiceNo, SUM( weight ) , COUNT( barcode ) , sum_total
FROM (SELECT * FROM `selected_items`
WHERE DATE LIKE '07-Jan-2016'
ORDER BY id DESC
)a
GROUP BY invoiceNo;
I didn't get it why you are using sub-query. You can directly use the table 'selected_items' and check the condition in where clause.Like:
SELECT invoiceNo, SUM(weight), COUNT(barcode)
from 'selected_items'
WHERE date LIKE '07-Jan-2016'
GROUP BY invoiceNo
Order By Id
You dont need to do order by inside inner select query. And in MySQL, you need to give an alias to a derived table, a in this example.
SELECT invoiceNo, SUM(weight), COUNT(barcode), sum_total
FROM
(
SELECT * FROM `selected_items` WHERE date LIKE '07-Jan-2016'
) a
WHERE date LIKE '07-Jan-2016' GROUP BY invoiceNo;
Without looking at data, it is difficult to decide to order by but this query will work for you.
You're query is almost right. However there's only missing. You must used an ALIAS.
SELECT * FROM
(
SELECT * FROM #table
)AS tbl1 WHERE field1 = 'test'

MySQL order results by date after a group by

We are working on a project for school and have a small issue with a query.
What we try to do is the following:
Select the education-unit(s) with the same version_vid and after that select the education-unit with the latest version_date.
But whatever we try, the education-unit with the lowest euid is returning.
We are using the Yii2 framework for this project, the ActiveQuery we use is:
EducationUnit::find()->groupBy('version_vid')->orderBy('version_date DESC');
SQL Fiddle:
http://sqlfiddle.com/#!9/9929d/2/0
Thanks in advance!
Maybe this can help you:
EducationUnit::find()
->from('select * from education_unit ORDER BY version_date DESC')
->groupBy('version_vid')
->all();
Wrap a select around your query, after that do the group by:
SELECT * FROM
( SELECT * FROM `education_unit` ORDER BY `version_date` DESC ) a
GROUP BY a.`version_vid`
Why it didn't work in your query is because SQL has an execution plan as below:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
The reason you are getting the lowesteuid is that the ORDER BY is applied after the GROUP BY and the GROUP BY is choosing arbitrary values from the group to return.
This is a classic top in group question and has been answered previously
I personally like the answer supplied by Bill Karwin which when applied to your situation becomes:
SELECT t.*
FROM table t
LEFT JOIN table t2
ON t2.version_vid = t.version_vid
AND t2.version_date > t.version_date
WHERE t2.version_vid IS NULL
Another common solution is:
SELECT t.*
FROM table t
JOIN (
SELECT version_id, MAX(version_date) version_date
FROM table
GROUP BY version_id
) t2
ON t2.version_id = t1.version_id
AND t2.version_date = t1.version_date

MySQL GROUP BY ignoring ORDER BY clause

I have two queries, the only difference being the GROUP BY clause
SELECT * FROM `packages_sorted_YHZ` WHERE `hotel_city` = 'Montego Bay'
ORDER BY `deal_score` DESC
LIMIT 0,3;
SELECT * FROM `packages_sorted_YHZ` WHERE `hotel_city` = 'Montego Bay'
GROUP BY `hotel_name`
ORDER BY `deal_score` DESC
LIMIT 0,3;
The first query returns the first result with a deal_score of 75 but the second query returns the first result with the deal_score of just 72.
I would have thought that regardless of the GROUP BY clause, the first result would have the highest deal score possible (75)
The purpose of the GROUP BY clause is to optionally select a unique hotel_name for each result.
Does anyone know what I'm doing wrong here.
Without being able to look at all the data, my best guess is that Group By is merging the data and giving you an arbitrary value that matches the Where clause. This will happen if hotel name isn't unique, and you won't be given the maximum score unless you specifically query for it.
Try putting a Max() around deal_score. In MySQL, Group By can be used way too easily, I like how MSSQL enforces the use of aggregate functions and grouping by every field that isn't aggregated. Try this query:
SELECT `hotel_name`, MAX( `deal_score` ) AS `max_score` FROM `packages_sorted_YHZ` WHERE `hotel_city` = 'Montego Bay'
GROUP BY `hotel_name`
ORDER BY `max_score` DESC
LIMIT 0,3;
It looks like you are facing some very MySql specific issue. In theory, your second query is not valid and should return an error. But MySQL allows for selection of so called hidden columns - the columns that are not mentioned in a group by clause and not aggregated.
As stated in manual, hidden columns values are indeterminate, but in practice it usually picks up the first row walking the index used, regardless of sorting specified by ORDER BY, as sorting is performed after the grouping.
This is vendor-specific issue, so your second query should always fail if used to query other RDBMS. The correct implementation should be something like
SELECT max(`deal_score`) as maxdeal, `hotel_name` FROM `packages_sorted_YHZ` WHERE `hotel_city` = 'Montego Bay'
GROUP BY `hotel_name`
ORDER BY maxdeal
LIMIT 0,3;
You should not use GROUP BY but instead DISTINCT since you want a unique hotel_name.
example:
SELECT DISTINCT hotel_name -- add other fields here
FROM `packages_sorted_YHZ`
WHERE `hotel_city` = 'Montego Bay'
ORDER BY `deal_score` DESC
LIMIT 0,3;
SELECT max(deal_score) as maxdealscore, `hotel_name` * FROM `packages_sorted_YHZ` WHERE `hotel_city` = 'Montego Bay'
GROUP BY `hotel_name`
ORDER BY `deal_score` DESC
LIMIT 0,3;

MYSQL position of row by order

I have had a look through google results, but can't find a simple answer, I have a table
id, points (and more fields, but they dont affect anything)
How would I go about Getting position of record 24(id) ordered by points DESC?
I'm not sure I've understood your question
select * from table order by points desc limit 23,1
Select Count(*) from (
Select ID from UnNamedTable A where A.points>(Select B.Points from UnNamedTable B where B.ID=24)
)
Are you trying to figure out out what place a user is in based on a points system?
If so then just find how many users have more points than a particular user then add 1.
SELECT COUNT(*) + 1 AS 'position' FROM table WHERE points >
( SELECT points FROM table WHERE id = someIDhere )
You could create a variable to keep track of your row position after sorting. Something like this would work:
select #rownum:=#rownum+1 ‘rank’, p.* from table1 p, (SELECT #rownum:=0) ID order by Points desc limit 10;

Categories