MYSQL ORDER BY CASE stored value - mysql

Im trying to show first the value that is stored in the 'zone' field, since each customer has different value, I want the one in his ZONE to show first in his lists. Thanks
first run a query for using the VAR later
$data = "SELECT * FROM users;
$datas = mysqli_query($con,$data) or die(mysqli_error($con));
$query = mysqli_fetch_array($datas);
Now I can use the {$query['zone']} and show those first in the query
"SELECT * FROM users WHERE ORDER by zone CASE zone WHEN '{$query['zone']}' THEN 0 ELSE 2'";
Im not getting the expected results, any advice? Thanks

I think you want something like this:
ORDER by (zone = '{$query['zone']}') desc,
zone
This assumes that the expression '{$query['zone']}' is the zone that you want to give priority to. User's whose zone's match this will appear first.

Related

How to save the query result in a variable and use it in another query

I want to save the last generated voucher in a variable and used as an input for another query..
$last = $this->db->query('SELECT MAX(voucherno) AS `last` FROM `purchasebill` ORDER BY no DESC LIMIT 1')->row_array();
$result = $this->db->query("SELECT * FROM `purchaseitem` where vno= '$last[0]' ORDER BY vno " )->result_array();
I tried like the above code it gives me an error undefined offset 0..Help me to save the last generated voucher no in an last variable
As per the document, $last[0] will return entire first row. In your case you want to access the value of MAX(voucherno) which is stored in an alias last.
Change $last[0] to $last['last'] in your next query and it shall work.
"SELECT * FROM `purchaseitem` WHERE vno = '{$last['last']}' ORDER BY vno"

MySQL Get "id" from select

I have a select statement:
SELECT id, content, name
FROM records
WHERE type = '1'
AND name = 'test';
Here's the output:
id content name
99708 10.6.252.41 server01.example.org
What I'd like to do is be able to get the id that is returned from the previous statement and USE the id as input into another statement (an UPDATE statement) that will increment the value of a single column in the same table.
An example UPDATE statement that I am wanting is:
update records SET hits = hits + 1 WHERE id = ID_FROM_SELECT;
Thanks in advance.
You can use user defined session variables for this if the SELECT is returning just one result:
SELECT #id:=id AS id, content, name
FROM records
WHERE type = '1'
AND name = 'test';
Then, on the same database session (connection), do the following:
UPDATE records
SET hits = hits + 1
WHERE id = #id;
I'm assuming you're doing something with the selected records in your app, and you're trying to save on performance by avoiding having to search for the record again in the UPDATE. Though, in that case, why not set the 'id' value as a parameter in code?
Obviously, if the SELECT is returning multiple records, this would best be done in code as I mentioned above, otherwise you're left with running the SELECT query again as a subquery:
UPDATE records
SET hits = hits + 1
WHERE id IN
(SELECT id
FROM records
WHERE type = '1'
AND name = 'test');
So, then, it makes more sense just to apply the same filter to the UPDATE instead:
UPDATE records
SET hits = hits + 1
WHERE type = '1'
AND name = 'test'
Probably this is not what you want to do.
First of all...If the query only returns 1 line, the solution provided by Marcus Adams works fine. But, if the query only returns one line, you dont need to preset the id in order to update. Just update it:
update records
set hits = hits + 1
where type = '1'
and name = 'test'
Second...If the query will not return only one record and you want to update all records returned with same values or calculations, the same code above will do what you need.
Third, if the query does not return just one record and you need to update each record returned with different value then you need to have a different approach.
I think you are not designing your system very well. If the request for update come from outside, you should have the id to be updated as a parameter of your request. For example something like:
<html>
<body>
Test
</body>
</html>
And in your update.php you have something like:
<?php
$id = $_GET['id'];
$sql = "update records set hits = hits + 1 where type = '1' and name = 'test' and id = $id";
?>
Of course, the picture I have is to small. Probably you have a reason to do this way or this is just an example. If you fill us up with more info we might be more helpful.

How can I "order by" only the LIMIT results in a mysql Query?

Hi I need to get the results and apply the order by only in the limited section. You know, when you apply order by you are ordering all the rows, what I want is to sort only the limited section, here is an example:
// all rows
SELECT * FROM users ORDER BY name
// partial 40 rows ordered "globally"
SELECT * FROM users ORDER BY name LIMIT 200,40
The solution is:
// partial 40 rows ordered "locally"
SELECT * FROM (SELECT * FROM users LIMIT 200,40) AS T ORDER BY name
This solution works well but there is a problem: I'm working with a Listview component that needs the TOTAL rows count in the table (using SQL_CALC_FOUND_ROWS). If I use this solution I cannot get this total count, I will get the limited section count (40).
I hope you will give me solution based on the query, for example something like: "ORDER BY LOCALLY"
Since you're using PHP, might as well make things simple, right? It is possible to do this in MySQL only, but why complicate things? (Also, placing less load on the MySQL server is always a good idea)
$result = db_query_function("SELECT SQL_CALC_FOUND_ROWS * FROM `users` LIMIT 200,40");
$users = array();
while($row = db_fetch_function($result)) $users[] = $row;
usort($users,function($a,$b) {return strnatcasecmp($a['name'],$b['name']);});
$totalcount = db_fetch_function(db_query_function("SELECT FOUND_ROWS() AS `count`"));
$totalcount = $totalcount['count'];
Note that I used made-up function names, to show that this is library-agnostic ;) Sub in your chosen functions.

Mysql like search with more than one column

I have a drupal site with the search option. If user enters the search keyword, i need to compare that with more than one columns and display the records.
I have tried the following query
$search = 'test';
$sql_query = db_select('logoinfo', 'l')->fields('l');
$or = db_or();
$or->condition('search_field', '%'.db_like($search).'%','LIKE');
$or->condition('companyname', '%'.db_like($search).'%','LIKE');
$sql_query->condition($or);
$selectlogos = $sql_query->execute();
It displays all the records matching the search keyword with the order of auto increment Id asc.
But i want to display the records first which is having both search_field and companyname matches with the keyword, after that other records which is matches with either companyname or search_field. Please advise to achieve this.
Since orderBy requires a field name and can't order by an expression, you'll need to use addExpression to get an alias and then order by that alias. The expression in my example will return 0 if the value is not in both fields and 1 if it is in both fields. As far as I know this should be standard SQL, but it may vary on different database backends; so the expression may need to be adjusted depending on the database you are using.
<?php
$search = 'test';
$sql_query = db_select('logoinfo', 'l')->fields('l');
$or = db_or();
$or->condition('search_field', '%'.db_like($search).'%','LIKE');
$or->condition('companyname', '%'.db_like($search).'%','LIKE');
$sql_query->condition($or);
$safe_search = db_like($search);
$ex_alias = $sql_query->addExpression("l.search_field LIKE '%$safe_search%' AND l.companyname LIKE '%$safe_search%'");
$sql_query->orderBy($ex_alias, 'DESC');
$selectlogos = $sql_query->execute();
?>

Cast function output as column name

I have come across a scenario where I need to "cast" the output of a function as the column name I want to select:
(SELECT
LOWER(DATE_FORMAT(NOW(), '%b'))
FROM lang_months
WHERE langRef = lang_statements.langRef
) AS month
Just returns the current month which is expected, but I want this to select the column called "may" in this case.
How would I do this?
Thanks, your answer gave me an idea. I just put the current date into a variable and used that in the query like so:
$thisMonth = strtolower(date('M')) ;
(SELECT
$thisMonth
FROM lang_months
WHERE langRef = lang_statements.langRef
) AS month
This is not possible. The name of an entity must be known when the query reaches MySQL.
The easiest option would probably be to determine the column name in whatever language you're using then to just use that. For example, in PHP:
$col = 'someAlias';
$query = "SELECT blah as `{$col}` FROM tbl";
I don't think this is possible.
You could create a view that offers this view on your data so you can they query it more expressively, but you're still going to have to write those 12 subqueries and aliases by hand.
This should work:
$month = LOWER(DATE_FORMAT(NOW(), '%b')); // Results in 'may'
$result = mysql_query('SELECT * FROM $month'); // Returns all records in table 'may'