I'm sorry I'm weak for English.
i echo 2 row in each page . how echo next 2 row
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category
WHERE mzmx_post.id = mzmx_post_category.post_id AND zmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2
You can use the two-arguments form of LIMIT to offset the result by a given number of rows, like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2, 2 -- fetch records 3 and 4
This gives you the second page. If you want the third page, then:
LIMIT 4, 2
And so on.
Note that I modified your query so the joining condition between the tables is placed in the ON clause of the join rather than in the WHERE clause.
Better add one extra column (e.g. mzmx_post_key bigint) of Long type in each table and have sequential value on that column. Use that column to fetch data from DB from page wise.
sqL suery should look like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5 and mzmx_post_key> ##last record key##
ORDER BY mzmx_post_key ASC
LIMIT 2
The basic idea is to use
LIMIT n,o
where n is the results per page
o is the offset from the first result
for the p-th page the offset would be
o = p * n
where p = 0,1,2,....
Related
I was trying to create a single SQL query to return what I need, instead of creating 2 querys, but I need to use the result of one of the querys as the offset of the other one.
My table has user answers with scores, each user may have multiple answers in that table. And I want to calculate the middle point of the table of ordered scores.
Example:
User answers:
User 1 - 5 points
User 1 - 15 points
User 2 - 8 points
User 3 - 12 points
Ranking Table:
User 1 - 20 points
User 3 - 12 points < Middle point
User 2 - 8 points
Solution:
The first query calculates the middle point:
SELECT CEILING(count(Distinct(id_user)) / 2) as position
FROM us_user_response
where id_round=1
Query result:
position : 2
This second query creates the ordered ranking table:
SELECT sum(points) as score
FROM us_user_response
where id_round=1
GROUP BY id_user
Order by score DESC
Now I want to create one big query that returns the score of the middle user, I just need to use the first query result as offset of the second query:
SELECT sum(points) as score
FROM us_user_response
where id_round=1
GROUP BY id_user
Order by score DESC LIMIT 1
OFFSET (SELECT CEILING(count(Distinct(id_user)) / 2) as position
FROM us_user_response where id_round=1)
Of course, this doesn't work, is there any way to use a result as offset?
EDIT:
The queries work nice! My question is if there is any way to use the result of a query as the offset of another. So I could accomplish this in one single query.
Try something like this:
SET #line_id = 0;
SET #line_offset = (
SELECT CEILING(count(Distinct(id_user)) / 2) as position
FROM us_user_response
WHERE id_round = 1
);
SELECT sum(points) as score,
IF((#line_id := #line_id + 1) = #line_offset, 1, 0) AS useit
FROM us_user_response
WHERE id_round = 1
GROUP BY id_user
HAVING useit = 1
ORDER BY score;
Hello there i am having little problem. I have two tables in my database.
As you can see i am getting all employees in one tab, and what i am trying to achieve here is to display only relevant employees in given tab. So employees from Customer services wont be displayed in Sales tab for example.
$query = mysql_query("SELECT * "."FROM employees, dept_emp "."WHERE employees.emp_no = dept_emp.emp_no");
Thank you for looking and help :)
Your WHERE clause is useless as it is just restating a JOIN condition basically. Try this:
SELECT *
FROM employees AS e
INNER JOIN dept_emp AS de ON e.emp_no = de.emp_no
WHERE de.dept_no = '?'
Obviously the ? would be substituted with the dept_no value you are actually trying to filter on.
Per your question about seeting query limits/pagination, that is done via SQL LIMIT clause. The clause can be expressed in a few different ways.
This first just returns a max number of rows:
LIMIT 100 <-- shows first 100 rows from the result set
The following two forms of syntax are used for pagination of results:
LIMIT 0, 100 <-- show first 100 rows from the result set (start at 0 offset, and return a max of 100 rows
LIMIT 100, 100 <-- show rows 101-200 from the result set (start at 100 offset and return max of 100 rows)
Or:
LIMIT 100 OFFSET 0 <-- first 100 rows
LIMIT 100 OFFSET 100 <-- rows 101-200
So putting it all together
SELECT *
FROM employees AS e
INNER JOIN dept_emp AS de ON e.emp_no = de.emp_no
WHERE de.dept_no = '?'
ORDER BY e.emp_no
LIMIT 0,100
Note that I also added an ORDER BY clause. This is important for pagination in that just a regular unordered SELECT doesn't guarantee order. If you tried to paginate without an ORDER BY you could potentially get the same row returned in multiple "pages".
It doesn't appear you are limiting the departments. The where clause needs a hard limit, your where will always match everything. Also, why are you concatenating your statement? It doesn't break.
Something like:
$query = mysql_query("SELECT * FROM employees JOIN dept_emp ON employees.emp_no = dept_emp.emp_no WHERE dept_emp.dept_no = 'd007'");
$dept = ?;
$query = mysql_query("SELECT *
FROM employees, dept_emp
WHERE employees.emp_no = dept_emp.emp_no
AND de.dept_no = $dept
");
I am wondering of someone could help me out.
I want to display random 'polls' on my website, I have about 50 in my database and I want to display one different one each time the person reloads the page.
To get the poll, I am using the following SQL query .... But this gets the first one in the table ... how can I tell it to get a random 'poll'
SELECT *
FROM polls
LEFT JOIN pollanswers ON polls.pollID = pollanswers.pollID
WHERE polls.pollID = 1
ORDER By pollAnswerListing ASC
Thanks much
Use ORDER BY RAND() LIMIT 1, and probably remove the WHERE clause, assuming polls.pollID is your primary key.
SELECT *
FROM polls
LEFT JOIN pollanswers ON polls.pollID = pollanswers.pollID
/*WHERE polls.pollID = 1*/
ORDER BY RAND() LIMIT 1
You have to change the pollID to some random number
polls.pollID = 1
to e.g.
polls.pollID = 9
Generate a Random number between 1 and 50 (assuming you have 50 polls)
and pass that to your mysql query as PollId value instead of the hard coded value 1
var randomId= rand(5, 50);
Use this randomId in your query
I have a mysql table. It has auto increment on the id. but I regularly delete rows so the numbers are all over the place. I need to get the last n rows out, but because of deletions, the common way of using the max of the autoincremented id column doesn't work well...
1 - Is their another way to get the bottom 50?
2 - Is their a way to get rows by actual row number? so if I have 4 rows labelled 1,2,3,4 delete row 2 then it will become 1,2,3 rather than 1,3,4?
SELECT ... ORDER BY id DESC LIMIT 50
SELECT *
FROM TABLE
ORDER BY id DESC
LIMIT 50
EDIT
To pick the last 50, but sort by id ASC
SELECT X.*
FROM ( SELECT *
FROM TABLE
ORDER BY id DESC
LIMIT 50
) X
ORDER BY X.id
1 - First get total row count like
SELECT COUNT(*) AS c FROM ...
then use
SELECT ..... LIMIT [start],[count]
2 - One idea is to use view , or procedure, but this is much more harder and may be used when there is no other way to avoid this
1 - Is their another way to get the bottom 50?
SELECT * FROM table_name ORDER BY record_id DESC LIMIT 50
2 - Is their a way to get rows by actual row number? so if I have 4 rows labelled 1,2,3,4 delete row 2 then it will become 1,2,3 rather than 1,3,4?
SELECT * FROM table_name
1 - Yes but it is ugly afaik, you do a
SELECT whateveryouwant FROM table ORDER BY yourprimarykey DESC LIMIT 50
the you fetch the rows into an array and reverse the array, in php :
$r = mysql_query('SELECT * FROM table ORDER BY primarykey DESC LIMIT 50');
$set = array();
while($row = mysql_fetch_assoc($r)) $set = $row;
$set = array_reverse($set);
foreach($set as $row) {
// display row ...
}
2 - You'll have to manage your primary key by yourself, its a bit risky ...
I am coding a blog post kind of thing, where the author will post the article and it will be displayed in the front end, my problem starts for selecting the posts as i have to meet certain conditions for posting the news in the front end,
I have 4 fields in the database namely
title
pic_title
pic_brief
pic_detail
you guessed it right apart from the title table the rest of three will hold the path to the images in varchar datatype, which will be used to display as the post, the format of the front end is such that
a) there will be total of eight post
displaying in the front end (eight
entries from the database)
b) there will be three post on the top which will include the value from
the table title, pic_title and
pic_brief (total of 3 values)
c) and the rest five will contain just the title and pic_title
(excluding the three entries of top)
Please NOTE: i want the second query to exclude the top 3 record
which already exist in the top i.e
(first query = 3 post in descending
order, second query = 8 - first 3 = 5
post)
The Order of the Post i want is by id DESC
EDIT: I took the first query as
SELECT * FROM news ORDER BY id DESC LIMIT 3
Now if i take the same second query and try populating the values by desc order again the same records will be accessed
In simple words i want a query that will skip the last three records order by id DESC
How do i achieve this feat in PHP?
If you just want the SQL, here it is:
First query
SELECT * FROM `table` LIMIT 3
Second query
SELECT * FROM `table` LIMIT 3,5
(where table is the name of your table of course. Of course you may want to add some ORDER BY clause. To execute these queries in PHP, I suggest reading the manual. If you have any specific problems after doing so, then you can post a new question.
This is a situation where I'd likely opt to select all eight records at once - the less trips to the database, the better.
SELECT t.title,
t.pic_title,
t.pic_brief
FROM TABLE t
ORDER BY t.id DESC
LIMIT 8
...because the rest is just presentation:
$query = sprintf("SELECT t.title,
t.pic_title,
t.pic_brief
FROM TABLE t
ORDER BY t.id DESC
LIMIT 8");
// Perform Query
$result = mysql_query($query) or die( mysql_error() );
$rowcount = 1;
// Use result
while ($row = mysql_fetch_assoc($result)) {
if(rowcount <= 3) {
echo $row['title']
echo $row['pic_title']
echo $row['pic_brief']
} else {
echo $row['title']
echo $row['pic_title']
}
++$rowcount;
}
first query will be like this
"select title, pic_title , pic_brief from table_name order by post_id desc limit 0 , 3"
and rest of five will be
"select title, pic_title from table_name order by post_id desc limit 3 , 5"
second query will exclude the three results returned by first query...
If you want more perfection you can collect all three Ids returned by first query and can add NOT IN in second query.
"select title, pic_title from table_name where post_id not in (1,2,3) order by post_id desc limit 0 , 5";