在Swift中使用FMDB从多个表中进行选择

时间:2016-06-06 12:30:17

标签: swift sqlite fmdb

我正在寻找一种方法,使用Swift中的FMDB从7个不同的表中打印出四个特定的列。我尝试用点符号选择它们,但这似乎不起作用。

DB看起来像这样:

  • 艺术家:[ArtistId],[姓名]
  • 追踪:[TrackId],[AlbumId],[Name]
  • 专辑:[AlbumId],[Name],[ArtistId]
  • 类型:[GenreId],[姓名]
  • 发票:[CustomerId],[InvoiceId]
  • InvoiceLine:[InvoiceId]
  • 客户:[CustomerId],[FirstName],[LastName],[City]

import Foundation

let database = FMDatabase(path: " /path to database.sqlite/ ")

database.open()

let rs = try database.executeQuery("SELECT Artist.Name, Track.Name, Album.Title, Genre.Name 
                                    FROM Invoice, Customer, InvoiceLine, Track, Album, Artist, Genre
                                    WHERE Customer.FirstName = 'Michelle'
                                    AND Customer.LastName = 'Brooks' 
                                    AND Customer.City = 'New York'
                                    AND Invoice.CustomerId=Customer.CustomerId 
                                    AND InvoiceLine.InvoiceId = Invoice.InvoiceId 
                                    AND Track.TrackId = InvoiceLine.TrackId 
                                    AND Album.AlbumId = Track.AlbumId 
                                    AND Artist.ArtistId = Album.ArtistId
                                    AND Genre.GenreId = Track.GenreId ", values: nil)

while rs.next() {
    let artistName = rs.stringForColumn("Artist.Name")
    let trackName = rs.stringForColumn("Track.Name")
    let albumTitle = rs.stringForColumn("Album.Title")
    let genre = rs.stringForColumn("Genre.Name")

print (artistName + " " + trackName + " " + albumTitle + " " + genre)
}

1 个答案:

答案 0 :(得分:0)

问题是stringForColumn(使用sqlite_column_name)函数正在使用基础表的列名,而忽略了表的名称。更糟糕的是,如果您有两个相同名称的列,则无法知道您希望从哪个表中获得结果。

所以,有两种解决方法:

  1. 您可以为列添加唯一名称:

    let rs = try database.executeQuery("SELECT Artist.Name AS ArtistName, Track.Name AS TrackName, Album.Title, Genre.Name AS Genre.Name ..."
    

    然后

    let artistName = rs.stringForColumn("ArtistName")
    let trackName = rs.stringForColumn("TrackName")
    let albumTitle = rs.stringForColumn("Title")
    let genre = rs.stringForColumn("GenreName")
    

  2. 使用列号:

    let artistName = rs.stringForColumnIndex(0)
    let trackName = rs.stringForColumnIndex(1)
    let albumTitle = rs.stringForColumnIndex(2)
    let genre = rs.stringForColumnIndex(3)