LIMIT clause similar to the MySQL in MSSQL - php

I must execute the query below in PHP with SQLServer, however I can not use the missing LIMIT clause in Microsoft queries.
$SqlTabelaAtual="SELECT *
FROM BusinessCadTabPreco
RIGHT JOIN BusinessCadTabPrecoItem ON BusinessCadTabPreco.CdTabela = BusinessCadTabPrecoItem.CdTabela
WHERE BusinessCadTabPreco.CdEmpresa =01
AND CdProduto =".$row['CdProduto']."
ORDER BY BusinessCadTabPreco.DtSincronizar DESC LIMIT 1

Use this code, in SQLServer the keyword Limit is TOP
$SqlTabelaAtual="SELECT TOP 1 *
FROM BusinessCadTabPreco
RIGHT JOIN BusinessCadTabPrecoItem ON BusinessCadTabPreco.CdTabela = BusinessCadTabPrecoItem.CdTabela
WHERE BusinessCadTabPreco.CdEmpresa =01
AND CdProduto =".$row['CdProduto']."
ORDER BY BusinessCadTabPreco.DtSincronizar DESC"

You can limit the records returned by adding the TOP expression to your SELECT clause.
Usage
/* Returns the first 10 records.
* Combine with an ORDER BY if you want control over the records returned.
*/
SELECT TOP 10
Id
FROM
TableName
;
Or
-- Percent return.
SELECT TOP 10 PERCENT
Id
FROM
TableName
;

Related

mysql select rows with top max value

i have a table in mysql with columns: id , view , agree.
i have upload my table's image below:
i want to select 8 rows that greater than others in view column. my condition is agree = 1.
can you tell me how can i do it by mysql query or php.
Select * from table_name WHERE agree = 1 ORDER BY view desc LIMIT 8
Try this:
SELECT * from table
WHERE agree = 1
ORDER BY view DESC
LIMIT 8
use limit and order by
Select * from mytable
where aggree=1
ORDER BY view DESC
LIMIT 8
You can do this:
SELECT *
FROM yourTableName
WHERE agree = 1
ORDER BY view DESC
LIMIT 8
You have to use ORDER BY clause.
SELECT * FROM <TABLE_NAME> WHERE AGREE = 1 ORDER BY VIEW DESC LIMIT 8
Use ORDER BY for DESC or ASC sorting.
and For selection of 8 rows use Limit Data Selections From a MySQL Database
Select * from table_name WHERE agree = 1 ORDER BY view desc LIMIT 8
If you want to take the top 8 'view' values from the table the MySql query for that is:
SELECT * FROM tablename WHERE agree=1 ORDER BY view DESC LIMIT 8;
Note: Replace tablename with the actual name of your table

Mysql select last 20 rows, with while loop

I have 50+ rows and each have an id, how do i get the last 20 records and display each ones information with php.
Is the best way to use a loop? I want it to display the results quick and not miss any rows, is a loop the best way to go then?
This is the code that I have
$result = $mysqli_log->query("SELECT * FROM `$usern`");
while( $row = $result->fetch_array() ) {
$credit = $row['credit'];
echo $credit;
}
The MySQL query being executed doesn't specify any "order" to the rows; MySQL is free to return the rows in any order it chooses, so it's possible that the "last 20" rows on one run of the query might differ from the "last 20" rows on a second run.
(We do observe repeated behavior when the statement is re-executed; it usually takes some DML operations, the addition of an index, or an OPTIMIZE table statement, to actually get a change in the results returned... but the point is, there is no "last 20" rows in the table. In MySQL, it's just a set of rows.)
To specify a specific sequence of the rows, add an ORDER BY clause to the query. Assuming that you want to use the unique id column to order the rows, and you want the last 20 rows, and you want them returned in ascending id sequence:
SELECT t.*
FROM ( SELECT u.*
FROM `$usern` u
ORDER BY u.id DESC
LIMIT 20
) t
ORDER BY t.id
And, yes, processing rows "in a loop" in PHP, just like you demonstrate, is a normative pattern.
To limit the number of queries use Limit and order them desc by your ID
Select *
From `$usern`
Order By ID Desc
Limit 20
To Flip them back in the forward order you can use a derived table
Select *
From (Select ID, Test
From test
Order By ID Desc
Limit 3) d
Order By ID Asc
If you need the newest 20 records, you have to ORDER DESC the result set by ID and then LIMIT that set result to 20 records.
So you can
use something like this:
$result = $mysqli_log->query("SELECT * FROM `$usern` ORDER BY `ID` DESC LIMIT 20");
while( $row = $result->fetch_array() ) {
$credit = $row['credit'];
echo $credit;
}
Another good approach, if you are using associative keys like $row['credit'], is to use featch_assoc instead of featch_array (if your framework provides such a function)

SELECT FOUND_ROWS() return 1 in mysql

SELECT FOUND_ROWS() not working or return 1 i dont know where i do mistake
$qry ="SELECT SQL_CALC_FOUND_ROWS DISTINCT user_id, login_date
FROM login_members
WHERE (login_date BETWEEN '2012-02-13 00:00:00' AND '2013-02-13 23:59:59')
LIMIT 0, 10";
$rs = mysql_query($qry);
$total_records = mysql_result(mysql_query("SELECT FOUND_ROWS()"),0,0);
The accepted answer seems to be wrong. as it suggest an use of found_rows() after a query with LIMIT in it.
ANSWER: The question is about the RETURN 1 and in some case 0 as a result of found_rows();
it happens when some other query is exectued after your first select statment.
especially when you are using an IDE or some client to run your queries, some additiona 'preparational' queries are executed before and after your query.
and found_rows() will return the numer of result returned by the LAST query run on the server. which in this case is not the one we are expecting.
and hence the RETURN 1 or 0 error.
Verification:
You can verify this by enabling general logging on your server, and executing the queries.
you will see couple of additonal queries exectued between 'the first query and the found row query'.
FIX
stored procedure, or the ver old COUNT(*).
performance wise there is hardly any difference.
ADDITIONAL
if your object is to find the total number of rows returned then it's fine.
and the use of SQL_CALC_FOUND_ROWS becomes immaterial.
here is a general rule, LIMIT is not required for found rows, nor SQL_CALC_FOUND_ROWS.
But three of them can be used together to give a very useful result.
ie on running something like.
SELECT SQL_CALC_FOUND_ROWS * from some_table_name LIMIT 0,10;
SELECT FOUND_ROWS();
We will get the number of rows that would have been returned by the query had we run
SELECT * from sometable_name;
ie: without the LIMIT.
having said that,
SELECT * from some_table_name LIMIT 0, 10;
SELECT FOUND_ROWS();
would give us the total number of results which cos of the limit will be <=10. and doesn't server any practical purpose, but it's NOT an error.
A SELECT statement may include a LIMIT clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT, but without running the statement again. To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward:
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
The second SELECT returns a number indicating how many rows the first SELECT would have returned had it been written without the LIMIT clause.
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
use this query
$qry ="SELECT DISTINCT user_id, login_date
FROM login_members
WHERE (login_date BETWEEN '2012-02-13 00:00:00' AND '2013-02-13 23:59:59')
LIMIT 0, 10";
if the preceding SELECT contain SQL_CALC_FOUND_ROWS, but if the preceding SELECT doesn't contain SQL_CALC_FOUND_ROWS, FOUND_ROWS() return the number of rows returned by this preceding SELECT
should be :
$qry ="SELECT DISTINCT user_id, login_date FROM login_members
WHERE (login_date BETWEEN '2012-02-13 00:00:00' AND '2013-02-13 23:59:59')
LIMIT 0, 10";
$rs = mysql_query($qry);
$total_records = mysql_result(mysql_query("SELECT FOUND_ROWS()"),0,0);
echo $total_records // display total record count
There is no need to use SQL_CALC_FOUND_ROWS
For total records use simple:
$total_records = array_shift(mysql_fetch_row(mysql_query('SELECT FOUND_ROWS()')));
You have to set mysql.trace_mode to off.
Use this is in each php page.
ini_set("mysql.trace_mode", "0");
or you can set this on .htaccess file
php_value mysql.trace_mode "0"
Here:
<?php
ini_set("mysql.trace_mode", "0");
$qry ="SELECT SQL_CALC_FOUND_ROWS DISTINCT user_id, login_date
FROM login_members
WHERE (login_date BETWEEN '2012-02-13 00:00:00' AND '2013-02-13 23:59:59')
LIMIT 0, 10";
$rs = mysql_query($qry);
$total_records = mysql_result(mysql_query("SELECT FOUND_ROWS()"),0,0);
echo $total_records;
?>
SQL_CALC_FOUND_ROWS and FOUND_ROWS() can be useful in situations when you want to restrict the number of rows that a query returns, but also determine the number of rows in the full result set without running the query again. An example is a Web script that presents a paged display containing links to the pages that show other sections of a search result. Using FOUND_ROWS() allows you to determine how many other pages are needed for the rest of the result.
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
The second SELECT returns a number indicating how many rows the first SELECT
would have returned had it been written without the LIMIT clause.
In the absence of the SQL_CALC_FOUND_ROWS option in the most recent successful
SELECT statement, FOUND_ROWS() returns the number of rows in the result set
returned by that statement. If the statement includes a LIMIT clause, FOUND_ROWS()
returns the number of rows up to the limit. For example, FOUND_ROWS() returns 10
or 60, respectively, if the statement includes LIMIT 10 or LIMIT 50, 10.
$qry ="SELECT SQL_CAL_FOUND_ROWS *
FROM login_members
WHERE (login_date BETWEEN '2012-02-13 00:00:00' AND '2013-02-13 23:
59:59')
LIMIT 0, 10";
$rs = mysql_query($qry);
$total_records = mysql_query("SELECT FOUND_ROWS() as `found_rows`;");
echo $total_records // display total record count

mysql random from top 10

I have the mysql query:
SELECT * FROM bigtable WHERE column1='1' ORDER BY column2 DESC LIMIT 10
And then I put everything in an array and use php to choose a random row from this array of 10 items.
Is there a way to do this with a single mysql query instead of mysql+php part?
After take top 10, then take 1 with random:
SELECT * from (
SELECT * FROM bigtable
WHERE column1='1'
ORDER BY column2 DESC LIMIT 10
) T ORDER BY RAND()
LIMIT 1

How do I fetch the last 15 rows in a table, then the 15 before that?

I want to return only the last 15 rows in my table, then the 15 before that.
Unfortunately while($rows = mysql_fetch_assoc($result)) where the query is SELECT * FROM table returns the data in all rows.
I thought about doing something like:
In my insert script
SELECT * FROM table then $selection_id = mysql_num_rows($result)-14 before inserting any data, then adding column named selection_id which would contain $selection_id, thus each set of 15 rows would have the same selection_id.
In my select script
SELECT * FROM table then $num_rows = mysql_num_rows($result)/15 then SELECT * FROM table WHERE selection_id='$num_rows' and SELECT * FROM table WHERE selection_id='$num_rows-1'.
I could then perform while(..) on both results as usual.
However, I'm not sure this is the most efficient way (chances are it's not), so if not, I'd really appreciate some suggestions to cut down the amount of code I'll have to use :)!!
Use a LIMIT clause in your query, order by your auto-incrementing primary key in descending order. E.g.
SELECT * FROM `table` ORDER BY `selection_id` DESC LIMIT 0,15
...will get the last 15 rows, and:
SELECT * FROM `table` ORDER BY `selection_id` DESC LIMIT 15,15
...will get the 15 rows before that.
Selecting the last 15 rows:
SELECT *
FROM `table`
ORDER BY `id` DESC
LIMIT 0,15
Selecting the 15 rows before the previous ones:
SELECT *
FROM `table`
ORDER BY `id` DESC
LIMIT 15,15
And you can continue in a while cycle.
You need to check out mysql LIMIT. To get the last 15, you'd need to know the number of total rows.
$offset=$rowcount-15;
$sql="SELECT * FROM mytable LIMIT $offset,15";
This is just for example, you'd want to make sure there are at least 15 rows, I'm not sure how mysql would deal with a negative offset. I'll let you figure out how to count the rows.
Edit:
Oh, haha, you could also just sort it descending, that will save you having to query twice.
SELECT * FROM mytable ORDER BY id DESC LIMIT 15;

Categories