如何根据SQLite的相关表值从一组表中提取数据?

时间:2015-06-10 19:17:22

标签: mysql sqlite

我有一组表格:

1) **nanoInst**:
rid | api_id | name | instLoc | instText | pixelPitch | logo | listImg

2) **nanoFiles**:
rid | api_id | name | fileType | fileLoc

3) **nanoInd**: 
rid | api_id | name

4) **nanoRelInd**: 
rid | inst_id | ind_id

5) **nanoGalleries**: 
rid | inst_id | file_id | gallery_order

我的原始SQL语句简单地选择了nanoInst表中的id和名称,来自nanoFiles的fileLoc和来自nanoInd的名称,其中nanoInst存储了nanoFile id,并且nanoInst和nanoInd被实现了它们的ID。

SELECT 
nanoInst.rid as instID, 
nanoInst.name AS nanoName, 
nanoFiles.fileLoc AS nanoFile, 
nanoInd.name AS indName 
FROM nanoInst 
LEFT JOIN nanoFiles ON nanoInst.logo = nanoFiles.rid 
LEFT JOIN nanoRelInd ON nanoInst.rid = nanoRelInd.inst_id 
LEFT JOIN nanoInd ON nanoRelInd.ind_id = nanoInd.rid

我需要调整此声明,因此我只能获得nanoFiles.fileType是'视频'的结果。我试过简单地添加WHERE nanoFiles.fileType='video'但是返回了0行,但我知道有些行存在。

--- 编辑 ---

我发现如果我可以计算该行的视频项目数,那么运行WHERE子句进行过滤:

SELECT 
  nanoInst.rid as instID, 
  nanoInst.name AS nanoName, 
  nanoFiles.fileLoc AS nanoFile, 
  nanoInd.name AS indName, 
  nanoFiles.fileType as nanoType, 
  (SELECT
  COUNT(nanoGalleries.rid)
  FROM nanoGalleries
  LEFT JOIN nanoFiles ON nanoFiles.rid = nanoGalleries.file_id
  LEFT JOIN nanoInst ON nanoInst.rid = nanoGalleries.inst_id
  WHERE nanoFiles.fileType = 'video') AS vidCount
FROM 
  nanoInst 
  LEFT JOIN nanoFiles ON nanoInst.logo = nanoFiles.rid 
  LEFT JOIN nanoRelInd ON nanoInst.rid = nanoRelInd.inst_id 
  LEFT JOIN nanoInd ON nanoRelInd.ind_id = nanoInd.rid
WHERE vidCount > 0

问题是vidCount返回的视频总数不仅仅是该行的计数/ nanoInst.rid

2 个答案:

答案 0 :(得分:0)

由于nanoRelInd或nanoInd中没有匹配的记录,记录可能会被过滤掉。如果是这种情况,这应该有用。

SELECT 
  nanoInst.rid as instID, 
  nanoInst.name AS nanoName, 
  nanoFiles.fileLoc AS nanoFile, 
  nanoInd.name AS indName 
FROM 
  nanoInst 
  LEFT JOIN nanoFiles ON nanoInst.logo = nanoFiles.rid 
  LEFT outer JOIN nanoRelInd ON nanoInst.rid = nanoRelInd.inst_id 
  LEFT outer JOIN nanoInd ON nanoRelInd.ind_id = nanoInd.rid
WHERE 
  nanoFiles.fileType='video'

答案 1 :(得分:0)

根据原始帖子中的评论和您提供的sqlfiddle:

   SELECT * 
     FROM nanogalleries
LEFT JOIN nanofiles on(nanofiles.rid=nanogalleries.file_id)
    WHERE nanofiles.filetype='video';

http://sqlfiddle.com/#!9/e318a/1/0

根据评论更新了答案

   SELECT nanogalleries.inst_id,
          nanoinst.name                AS nanoName,
          nanoFiles.fileLoc,
          nanoInd.name                 AS indName,
          count(nanogalleries.inst_id) AS vidCount
     FROM nanogalleries
LEFT JOIN nanofiles  ON nanofiles.rid = nanogalleries.file_id
LEFT JOIN nanoinst   ON  nanoinst.rid = nanogalleries.inst_id
LEFT JOIN nanoRelInd ON  nanoinst.rid =    nanoRelInd.inst_id
LEFT JOIN nanoInd    ON   nanoind.rid =    nanorelind.ind_id
    WHERE nanofiles.filetype = 'video'
 GROUP BY nanogalleries.inst_id;

http://sqlfiddle.com/#!9/e318a/50/1