SQL:子查询,返回包含"最受欢迎的"外键

时间:2014-10-14 02:10:20

标签: sql foreign-keys subquery

模式:

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

你可以看到我被困在COUNT部分。我基本上想要这样,这个查询只会返回任何比其他相同类型的医学实验室进行更多测试的医学实验室。

示例:

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

1 个答案:

答案 0 :(得分:1)

子查询将计算每个实验室为每个测试完成的测试次数

外部选择将选择实验室,每个测试的最大测试计数

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