retrieving only part of the record in database
I have a database which contains some topics each with a title and some description. In the title page, I have to display all the titles and a few lines of description for that topic. When a user clicks on one topic then he is taken to a page where he can find the entire description. Exactly like stackoverflow site, where description of each question is displayed in short.
I was wondering is there a way we can retrieve such short description from the database directly or should the front end parse the retr开发者_运维知识库ieved record and truncate it accordingly? Is there a way to query for a short version of the record from the database directly. I am using MySql as my database and php to display web pages.
SELECT SUBSTRING(`title`, 0, 100) FROM `topics`
I would say the answer is found in this post: SQL Server substring breaking on words, not characters
You wouldn't want to just limit by a string length, since then you might cut off a word right in the middle. Instead, you would want to set your max length and then move back to the place where there is a space.
Another option would be to run this once and then update a field in the table that stores the truncated text. That way you could limit your extra SQL calls and yet still have the nicely-formatted summary text.
Best solution:
SELECT SUBSTRING_INDEX('your string', ' ', 10);
this will return your string upto 10 spaces.
Note: SUBSTRING cause you to cut off words right in the middle as suggested by @BiggsTRC
Reference
select LEFT (description, CHARINDEX(' ', description, 50) ) from topics
this seems to address my problem correctly... any way thanks for all the answers.
Do you mean a chunk of the text from a text field?
Like select left(LongTextField,200) from myTable
You can limit the value you get back with a cast like this: select title, cast(description as varchar(300)) from table
or you could store a less abrasive truncated description as a smallDescription or whatever in the table as well(then make your frontend let you mark it and it dissects it for you^^).
精彩评论