计算mysql中文件夹中的文件数

时间:2014-12-15 01:24:35

标签: mysql

我有这些表

Create table series (
    id_series Int NOT NULL AUTO_INCREMENT,
    name_series Varchar(100) NOT NULL,
    kcal Int NOT NULL DEFAULT 0,
    type Varchar(20) NOT NULL,
    id_user Int NOT NULL,
    UNIQUE (name_excercise),
    Primary Key (id_series)) ENGINE = MyISAM;

Create table excercise (
    id_excercise Int NOT NULL AUTO_INCREMENT,
    name_excercise Char(100) NOT NULL,
    date Date NOT NULL,
    start Time NOT NULL,
    end Time NOT NULL,
    km Double(10,2) NOT NULL,
    id_series Int NOT NULL,
    UNIQUE (id_excercise),
   Primary Key (id_excercise)) ENGINE = MyISAM;

它们基本上就像文件夹。系列有一个系列和内部的名称,后来有练习。我需要的是返回用户拥有的每个系列以及内部的练习数量。但是我遇到了麻烦,因为我没有传递任何具体系列的ID,它可以计算所有的练习。是否可以仅使用用户ID打印? 我基本上有这个:

"SELECT * FROM series WHERE id_user = $id_user" 

但需要将其与此相结合:

"SELECT COUNT(*) FROM excercise WHERE id_series = $id_series"

不需要id_series。

1 个答案:

答案 0 :(得分:1)

这是查询:

SELECT S.*, COUNT(E.id_excercise) AS NumOfExc
FROM series AS S
JOIN excercise AS E
   ON S.id_series = E.id_series
WHERE S.id_user = '$id_user'
GROUP BY E.id_series
UNION
SELECT *, 0 AS NumOfExc
FROM series
WHERE id_user = '$id_user'
AND id_series NOT IN (
    SELECT S.id_series AS id_series
    FROM series AS S
    JOIN excercise AS E
       ON S.id_series = E.id_series
    WHERE S.id_user = '$id_user'
    GROUP BY E.id_series
)

以上查询将显示您需要的内容。