MySQL/SQL retrieve first 40 characters of a text field?

后端 未结 5 2200
无人及你
无人及你 2020-12-01 10:39

How can I retrieve a text field from mysql db table, but not the entire text, just the few 40 or so characters.

Can this be done in sql or do I need to do it using p

5条回答
  •  一整个雨季
    2020-12-01 10:51

    SELECT LEFT(field, 40) AS excerpt FROM table(s) WHERE ...
    

    See the LEFT() function.

    As a rule of thumb, you should never do in PHP what MySQL can do for you. Think of it this way: You don't want to transmit anything more than strictly necessary from the DB to the requesting applications.


    EDIT If you're going to use the entire data on the same page (i.e., with no intermediate request) more often than not, there's no reason not to fetch the full text at once. (See comments and Veger's answer.)

提交回复
热议问题