Split FirstName and LastName in sqlite

后端 未结 2 1724
甜味超标
甜味超标 2020-12-09 12:05

I have a table in sqlite db called [tblbook] with a column [authors]. What I am trying to do in the sql is to split the author values to firstname and the lastname and sort

相关标签:
2条回答
  • 2020-12-09 12:27

    Unfortunately this functionality is missing from SQLite:

    • http://www.sqlite.org/lang_corefunc.html

    • Index of substring in SQLite3?

    Maybe you can feed your custom string position function to SQLite using http://www.sqlite.org/c3ref/create_function.html

    But if you really need it, there is a complex, ineffective workaround:

    http://sqlfiddle.com/#!7/e03a4/3

    1: create a numbers table/view

    2: join authors to numbers table, and choose the MIN position of the space

    3: now you can split the names

    SELECT
      substr( name, 1, pos-1) AS first_name,
      substr( name,    pos+1) AS last_name
    FROM (
          SELECT
            author.name,
            numbers.x AS pos
          FROM       author
          INNER JOIN numbers
          WHERE substr( author.name, numbers.x, 1) = ' '
          GROUP BY author.name
         ) AS a
    ORDER BY last_name;
    
    0 讨论(0)
  • 2020-12-09 12:28

    Another way (a little shorter) to write this would be

    SELECT 
      substr(BookAuthor, 1, instr(BookAuthor, ' ') - 1) AS first_name,
      substr(BookAuthor,    instr(BookAuthor, ' ') + 1) AS last_name
    FROM tblBook where id=3
    ORDER BY last_name
    

    This would apply for version 3.7.15 and beyond.

    0 讨论(0)
提交回复
热议问题