I have a blog with English and Swedish posts. I first wrote in English and then switched to Swedish.
My question is, If there is any way to only display post with a higher id?
Like:
select * FROM blog WHERE id is bigger than 100
Anyone get my drift and know if this is possible? :)
I don't want to delete the old posts, and I also don't want people to see them.
Thank you!
I think you mean
Select *
From blog
Where Id > 100
Order by ID DESC
See http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html for more information.
If the ID is auto-incremented, this will bring the newest articles first, and not display the one with ID smaller than 100.
Simple Try this
SELECT * FROM blog WHERE id > 100
Even though all the answers seem correct, it looks to me you actually want to have just the last 20 or so blog posts. In that case use LIMIT.
select * from blog order by id desc limit 20
If you are working with a system for showing posts, you might rather want to show the latest few posts, which can be done with a query like this:
SELECT * FROM `blog` WHERE ORDER BY `id` DESC LIMIT '100';
MySQL Select query have syntax for bigger then is > you can do
select * FROM blog WHERE id > 100
Hope above will help.
Related
I have a sql statement:
$feed=$conn->prepare("SELECT * FROM posts WHERE post_by=? OR id=? ORDER BY id DESC LIMIT 10");
$feed->bind_param("ii",$friend['id'],$like[id]);
$feed->execute();
The $friend['id'] is the id of a user's friend, $like[id] is the id of a like by the user's friend.
The posts fetched with this query appear in a page.
What I want is I want to know which all posts have been posted by the user's friends (Which all posts have been fetched using $friends['id']) and which all posts have been liked by the user's friends and appear in the feed(Which all posts have been fetched using $like['id'])
I want to know all possibilities I can try to achieve what I want.
I have tried varying my query with UNION ALL but it shows errors and I could'nt achieve what I want.
Currently there are no errors but I want the user to know how this post appeared in the newsfeed.
Hope you all get a good idea about my question and all types of hacks are also accepted as I want in someway to achieve the result I would also agree to change mt query nature.
Please comment for more info.
Thanks in advance.
SELECT *, post_by = ?postId AS post_by_friend
FROM posts
WHERE post_by = ?postId OR
id = ?friendId
ORDER BY id DESC
LIMIT 10
post_by_friend will be 1 if it matched the first condition, otherwise 0. I haven't benchmarked it, but this method should be faster than StuartLC's UNION suggestion.
What you can do is break the query up on its 'OR' clause into a UNION of two separate queries, and add a marker column to indicate whether the row was found by friend or by like:
SELECT *
FROM
(
SELECT *, 'Friend' AS HowFound
FROM posts
WHERE post_by= ?postId
UNION
SELECT *, 'Like' AS HowFound
FROM posts
WHERE id= ?friendId AND post_by <> ?postId
) x
ORDER BY id DESC
LIMIT 10;
You'll want to exclude rows which match both friend and post classifications from one of the selects, otherwise it will be reported twice (or, otherwise your app will need to combine them).
I'm no PHP guru, but I'm sure there is a way to name the parameters to allow the above exclusion.
The derived table is needed to order and restrict the overall result.
I'm new to Stackoverflow, and I'm pretty new to MSSQL too (I've been using MYSQL for a couple of years now), and I was wondering if anyone could please help me with a query I'm having trouble with?
I've made a story archive page for a site that I'm putting together, and it's working fine, but the only problem is that I want to archive everything except for the top 6 stories in my table.
I came across a piece of code which will ignore the top few results (6 in my case), but I'm a little bit stumped as to how to incorporate it into my query.
I've tried a few things but I keep getting error messages - I think I'm way off track.
Any help that anyone can give me would be hugely appreciated!
Thank you very much in advance:)
This is the query I found:
SELECT *
FROM PageContent
WHERE id NOT IN (
SELECT TOP 6 id
FROM PageContent
ORDER BY date)
This is my query:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER by PageId desc) AS RowNum
FROM PageContent WHERE pagestory_type = 'latest_news'
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN $qpage_srt and $qpage_fin ORDER by date desc";
If you have SQL Server 2012 you can try:
SELECT *
FROM PageContent
ORDER BY [date]
OFFSET 6 ROWS
Why can't you just use the TOP clause with a select from the table ordered by the column you need? Similar to the sample you found.
SELECT TOP X * -- add fields as needed
FROM PageContent
WHERE pagestory_type = 'latest_news'
ORDER BY PageId DESC
i dont find any difference in your query except the parameter variables
$qpage_srt and $qpage_fin
it should be #qpage_srt and #qpage_fin in Ms sql...
I have a discussion type page, where users can enter their replies on different subjects. For this, I have a table name replies with fields replyID, topicID, userID, replybody, time
On the page, where I display the result, I use this php command:
$run = mysql_query("SELECT * FROM replies WHERE topicID = $topicnumber ORDER BY time DESC Limit 5");
while($data= mysql_fetch_array($run)){
// do formatting and display data
}
as you can see, the page initially displays only 5 replies on a topic (after which, if interested, user clicks to visit the page where all replies are displayed).
the thing is, the above code displays correctly the recent 5 replies, but I want to change the order of its display. It shows the recent most reply on top, and older replies are displayed as we go down, but I want to change this order, showing the recent most reply on bottom.
I think I'm missing a very simple point here, since most of the website have this feature where recent most comments go down, but hey, "no question is small".
I don't think that's very easy in sql.
I would just load the results in an array and use array_reverse() to reverse the order. Then you can loop through the array and display the values like you do now.
Otherwise I think you need to do 2 queries, one to get the total amount and then one to limit your result set to the last x items.
Use a nested query to reverse the order in SQL:
SELECT *
FROM (
SELECT * FROM replies WHERE topicID = $topicnumber ORDER BY time DESC Limit 5
) AS a
ORDER BY time ASC
The inner query will return your most recent 5 records, while the outer query will reverse the sort order of those 5.
I have a "banners" table which has image names and paths to image files that will be randomly viewed each time visitor navigates to another page.
banners table consists of banner_id (auto_increment, unique, primary, tinyint), banner_name (varchar) and banner_path (varchar) fields.
Banners table will be editable via a control panel. New banners will be ADDED, some banner will be DELETED after a while, and may be UPDATED. General CRUD operations, you know...
Now... Because of my goal is showing banners randomly, I will need a random number generator function which gives ability to exclude specific ones.
To be more clear,
Let's say my table looks like this:
banner_id banner_name banner_path
--------- ------------ ------------
1 First Banner first_banner.jpg
2 Second Banner second_banner.jpg
3 Third Banner third_banner.jpg
I can get random ID by using PHP function like this easily: mt_random(1, 3);
But wait. What if I delete one of these banners?
banner_id banner_name banner_path
--------- ------------ ------------
1 First Banner first_banner.jpg
3 Third Banner third_banner.jpg
In this case, as random output becomes "2", what will happen? There is no a "2" banner_id'd row?? So I must exclude DELETED id's from random generator number range. Will this be the best practise? If so, how can I do that?
I'm completly open for any new ideas which will help me to do thing I want to do.
Please help me to figure out this problem...
Thanks
Thanks.
SELECT FLOOR(RAND() * COUNT(*)) INTO #offset FROM banners;
SELECT * FROM banners LIMIT #offset, 1;
Assuming you can live with the small race window, you could do
SELECT FLOOR(RAND()*COUNT(*)) AS bannercount FROM banners;
and fetch this into $bannercount, next run
SELECT * FROM banners ORDER BY banner_id LIMIT $bannercount,1
Why not just select a random row instead of using PHP to select a random ID to show?
SELECT * FROM `banners` ORDER BY RAND() LIMIT 0,1;
And if you have an array of ID's to exclude
SELECT * FROM `banners`
WHERE `banner_id` NOT IN (/* array values*/)
ORDER BY RAND() LIMIT 0,1;
you will create one array from available ids and generate random numbers from that array
I want to make a simple news system using PHP and MySQL, right now I got a working post and read system but there is only one problem, I want it to show the 10 latest news but instead it shows the 10 oldest news.
My question is: Is there a way to make MySQL return the results from the bottom of a table or do I have to first get the number of posts and then limit it to the very last 10 ones?
Here is the insert (title and text is escaped and time is time(), poster is not done yet):
mysql_query("INSERT INTO news (title, poster, text, time) VALUES ('$newstitle', '1', '$newstext', '$time')") or die(mysql_error());
And to retrive it (addnews echos it):
$myqr = mysql_query('SELECT * FROM news LIMIT 10') or die("Error running news query: ". mysql_error());
while($myres = mysql_fetch_array($myqr))
{
addnews($myres['id'], $myres['title'], "admin", date('l jS F Y - H:i:s', $myres['time']), $myres['text']);
}
So, short: I want to read the database backwards, is it possible?
Check out the ORDER BY clause. It allows you to sort rows by a column in ascending or descending order. The following query will return 10 news items, sorted by time in descending order.
SELECT * FROM news ORDER BY time DESC LIMIT 10
Simple, just add an "ORDER BY" clause to your SQL, e.g.
SELECT * FROM news ORDER BY time DESC LIMIT 10
you need to modify your query to sort by the date it was created. something like
SELECT * FROM news order by time DESC LIMIT 10
should work for you. I think its worth noting that if you do not specify an Order by clause, the order in which results are returned is not guaranteed. Right now, you happen to be getting them ordered by the time they were inserted ascending, however you cannot safely assume that will always be the case.
Assuming that id is the primary key:
SELECT * FROM new ORDER BY id DESC LIMIT 10
Use an ORDER BY clause.
Could you not simply Order By time Descending before LIMIT 10?
use
SELECT * FROM news ORDER BY time DESC LIMIT 10
You could also use
SELECT TOP 10 FROM news ORDER BY time DESC
I believe. Not sure if the 'top' clause is SQL Server only, though.