获取另一个表中的ROWS数

时间:2012-03-26 17:53:15

标签: sql join subquery

我有两张桌子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 个答案:

答案 0 :(得分:0)

我认为这应该通过LEFT OUTER JOIN来完成。