2012-03-26 75 views
0

我有兩個表格EXERCISE和EXERCISEUSER。我需要列出所有鍛鍊項目,並在查詢中添加一個附加字段,如果該鍛鍊存在於表格EXERCISEUSER中,將返回該字段。換句話說,如果用戶做了這個練習,我需要知道。如果是這樣,它將在EXERCISEUSER中有一排。在其他表格中獲取數量

我當前的查詢是:

SELECT 
    "E".*, 
    "T"."NAME" AS "LEVEL" 
FROM 
    "EXERCISE" AS "E" 
INNER JOIN 
    "EXERCISETYPE" AS "T" 
ON 
    E.STO_FK_EXERCISETYPEEXERCISE = T.PK_EXERCISETYPE 
INNER JOIN 
    "LEVEL" AS "L" 
ON 
    L.PK_LEVEL = E.STO_FK_LEVELEXERCISE 
WHERE 
    (
     E.STATUS = 1) 
AND (
     L.STATUS = 1) 
AND (
     L.PK_LEVEL = 5) 
ORDER BY 
    "T"."ORDER" ASC 

,我會提供PK_USER了。

謝謝!


那麼,我使用子查詢,並達到我想要的結果。

SELECT 
    "E".*, 
    "T"."NAME" AS "LEVEL", 
    (SELECT COUNT(*) FROM STOUSER.EXERCISEUSER AS EU WHERE EU.STO_FK_EXERCISEEXERCISEUSER = E.PK_EXERCISE AND EU.STO_FK_USEREXERCISEUSER = 5978) AS MAKE_EXER_NUM 
FROM 
    "STOUSER"."EXERCISE" AS "E" 
INNER JOIN 
    "STOUSER"."EXERCISETYPE" AS "T" 
ON 
    E.STO_FK_EXERCISETYPEEXERCISE = T.PK_EXERCISETYPE 
INNER JOIN 
    "STOUSER"."LEVEL" AS "L" 
ON 
    L.PK_LEVEL = E.STO_FK_LEVELEXERCISE 
WHERE 
    (
     E.STATUS = 1) 
AND (
     L.STATUS = 1) 
AND (
     L.PK_LEVEL = 5) 
ORDER BY 
    "T"."ORDER" ASC 

謝謝!

+1

如果您最後的編輯是解決您的問題,請將其作爲答案發布,並將其標記爲答案,而不是將其編輯爲原始問題。 – turbo 2012-03-26 18:48:12

+0

相關子查詢通常是查詢的最低效方式,而不是使用派生表。並且不要使用select *! – HLGEM 2012-03-26 19:39:43

+0

只有查詢優化器可以作爲判斷。 – 2012-03-26 20:35:39

回答

0

我認爲這應該做一個左外部聯接。