SQL:返回包含“0”的行的子查询;“最受欢迎”;外键
模式:SQL:返回包含“0”的行的子查询;“最受欢迎”;外键,sql,foreign-keys,subquery,Sql,Foreign Keys,Subquery,模式: test_record ----------------------------------------------- |test_id | type_id | patient_no | medical_lab | ----------------------------------------------- test_type ---------------------- |type_id | test_name | ---------------------- medical
test_record
-----------------------------------------------
|test_id | type_id | patient_no | medical_lab |
-----------------------------------------------
test_type
----------------------
|type_id | test_name |
----------------------
medical_lab
------------------------------
| lab_name | address | phone |
------------------------------
注意:type_id是引用test_id的外键
我需要找到最受欢迎的医学实验室。最受欢迎的医学实验室是一个比任何其他医学实验室进行更多的任何类型的测试的实验室
这就是我到目前为止所做的:
SELECT medical_lab
FROM test_record, test_type
WHERE medical_lab = lab_name
AND test_record.type_id = test_type.type_id
GROUP BY type_id
HAVING COUNT(type_id) // not sure what to put here
正如你所看到的,我被困在计数部分。我基本上想要它,这样这个查询将只返回任何进行了比其他同类医疗实验室更多测试的医疗实验室
例如:
lab example1 has conducted 10 tests of type 1
lab example2 has conducted 3 tests of type 1
lab example2 has conducted 2 tests of type 2
lab example3 has conducted 1 test of type 2
然后,此查询应返回:
lab example1 // because it has done 10 tests of type 1
lab example2 // because it has conducted 2 tests of type 2
子查询将计算每个实验室为每个测试完成的测试数 外部选择将选择每个测试具有最大测试计数的实验室
SELECT T.lab_name, T.test_name, MAX(testcount)
FROM
(
SELECT M.lab_name, TT.test_name, COUNT(TT.test_name) as testCount
FROM medical_lab M
JOIN test_record TR
ON M.lab_name = TR.medical_lab
JOIN test_type TT
ON Tt.type_id = TR.type_id
GROUP BY M.lab_name, TT.test_name
) T
GROUP BY T.lab_name, T.test_name