2017-06-02 138 views
0

首先,對於標題感到抱歉,但我真的不知道該怎麼說。 我有3個表格用於存儲章節,頁面和閱讀。使用mysql查詢檢查空結果

表是...

部分

idsection 
sectiontitle 

idpage 
pagetitle 
idsection 

讀取

idread 
idpage 
time 

我有一個簡單的查詢,列出sections像 -

SELECT * FROM sections WHERE 1; 

但我要表明如果section已經完全read,這意味着所有pages具有相同idsection已經read。我能想象的唯一方法是複雜的查詢,使用php for腳本會更簡單。

回答

0

嘗試下面:

select * from section s where idsection not in (select page.idsection from 
page where 
page.idsection=s.idsection and idpage not in (select idpage from read)); 

我用不是因爲u需要檢查所有頁面,而不是頁面的1。 所以我們應該得到不在讀的頁面(未讀)並且不要放在那裏。

如果你有1個部分有5個頁面,並且全部被讀取,它會在你的主查詢選擇會話的子查詢上給你空的結果。

如果你有1個部分有10個頁面,只有9個頁面被讀取,它將會在子查詢中給你10個頁面,並使主查詢中你的部分爲空(不在)。

+0

我選擇你的答案,因爲這對我來說是最容易理解的。謝謝 – Entretoize

+0

好,主要的是,上面的查詢幫助和工作? –

+0

它似乎工作,但它似乎也更簡單,在我的情況下使用PHP的工作,因爲我的表不是那麼簡單,查詢太大。 – Entretoize

0

這應該工作,但它使用group by,所以您必須添加每個項目,您也想在group by中選擇sections表格。

SELECT  dbo.sections.idsection, dbo.sections.sectiontitle, CASE WHEN SUM(dbo.[read].idread) IS NULL THEN 0 ELSE 1 END AS AllRead 
    FROM   dbo.page INNER JOIN 
          dbo.sections ON dbo.page.idsection = dbo.sections.idsection LEFT OUTER JOIN 
          dbo.[read] ON dbo.page.idpage = dbo.[read].idpage 
    GROUP BY dbo.sections.idsection, dbo.sections.sectiontitle