如何使用单个查询从两个表中检索数据?

时间:2011-01-14 10:13:34

标签: mysql

我需要一份活动清单,显示每项活动注册的每个性别的子女数量。

结构:

CREATE TABLE Child(
child_id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
pc_id INTEGER NOT NULL,
child_fname VARCHAR(20) NOT NULL,
child_lname VARCHAR(20) NOT NULL,
child_dob DATE NOT NULL,
child_gender ENUM ('F','M') DEFAULT 'F' NOT NULL,
CONSTRAINT FOREIGN KEY(pc_id) REFERENCES Parent_Carer(pc_id))
ENGINE=InnoDB; 

CREATE TABLE Child_Activity(
child_id INTEGER NOT NULL,
activity_name_id ENUM('Art','Football','IT') DEFAULT 'IT'  NOT NULL,
activity_day ENUM('Tuesday','Wednesday','Thursday') NOT NULL,
CONSTRAINT PRIMARY KEY(child_id,activity_name_id),
CONSTRAINT FOREIGN KEY(child_id)references Child(child_id),
CONSTRAINT FOREIGN KEY(activity_name_id)references Activity(activity_name_id) )
ENGINE=InnoDB;

我有这个查询

SELECT activity_name_id,
       COUNT(*)     AS 'Number of Children',
       child_gender AS 'Childs Gender'
FROM   child c,
       child_activity ca
WHERE  c.child_id = ca.child_id
GROUP  BY child_gender,
          activity_name_id;  

谢谢。

3 个答案:

答案 0 :(得分:2)


Select Child_Activity.activity_name_id, count(child_m.id) as boys,   count(child_f.id) as girls,   
FROM Child_Activity
INNER JOIN Child as child_m
ON (child_m.child_id = Child_Activity.child_id AND child_m.gender = 'M' )
INNER JOIN  Child child_f
ON (child_f.child_id = Child_Activity.child_id AND child_f.gender = 'F' )

我希望这有效

答案 1 :(得分:1)

使用joins

例如

SELECT * FROM Child AS c
JOIN Child _Activity as ca
ON c.child_id = ca.child_id

答案 2 :(得分:1)

谷歌'mysql表加入'以获取更多示例。您需要将以下字段替换为要返回的字段的名称。

SELECT fields FROM Child AS C
INNER JOIN Child_Activity AS CA
ON CA.child_id = C.child_id