从视图

时间:2016-07-29 14:15:07

标签: mysql sql subquery

我这里有四张表(研究,出版物,地点,药物)和由药物和研究之间的多对多关系引起的联接表。

我使用以下脚本创建了一个视图:

SELECT 
        `l`.`country` AS `country`,
        `l`.`latitude` AS `latitude`,
        `l`.`longitude` AS `longitude`,
        `l`.`region` AS `region`,
        `s`.`enrolment` AS `enrolment`,
        `s`.`diagnosis` AS `diagnosis`,
        `s`.`registry_ID` AS `registry_ID`,
        `s`.`status` AS `status`,
        `s`.`site_name` AS `site_name`,
        `s`.`study_no` AS `study_no`,
        `p`.`pub_year` AS `pub_year`,
        `p`.`URL` AS `url`,
        `p`.`authors` AS `authors`,
        `p`.`pubMedId` AS `pubMedId`,
        `p`.`pub_title` AS `pub_title`,
        `d`.`name` AS `name`
    FROM
        (((`VL`.`Location` `l`
        join `VL`.`Study` `s`)
        join `VL`.`Publication` `p`)
        join `VL`.`Drugs` `d`)
    WHERE
        ((`l`.`id` = `s`.`location_id`)
            and (`p`.`study_id` = `s`.`id`)
            and `d`.`id` in ((SELECT 
                `VL`.`Study_Drugs`.`drugses_id`
            FROM
                `VL`.`Study_Drugs`
            WHERE
                (`VL`.`Study_Drugs`.`studiesList_id` = `s`.`id`))))

现在,我需要的是子查询为我提供每个研究中可以找到的药物的完整列表,这就是我单独进行此查询时会发生的情况:

SELECT d.name
FROM VL.Drugs d
WHERE d.id IN(SELECT drugses_id
            FROM Study_Drugs
            WHERE studiesList_id = 'whatever id')

所以,问题是为什么它单独返回查询的完整列表,而不是作为View脚本的一部分使用的同一查询?

EDIT包含样本数据和希望的结果:

研究:

'2', 'Spleen', '70', NULL, 'KALA-AZAR MEDICAL RESEARCH CENTER, RAMBAG ROAD , MUZAFFARPUR,  BIHAR -842001, INDIA ', 'Published', '75', NULL, '68'

公开:

'12', 'http://www.ncbi.nlm.nih.gov/pubmed/10897369', 'Sundar S, Gupta LB, Rastogi V, Agrawal G, Murray HW.', '10897369', 'Short-course, cost-effective drugs with amphotericin B-fat emulsion cures visceral leishmaniasis.', '2000', '2'

位置:

'68', 'India', '26.118589', '85.400719', 'India Subcontinent'

药物(单独执行子查询时):

'Pentavalent Antimonial'
'Miltefosine'

所以,除了研究和出版物中的一些不必要的字段之外,我希望从我的视图中获得所有这些信息。最终值(药物)由与研究ID相关的所有药物组成,我现在每行得到的内容如下:

'India', '26.118589', '85.400719', 'India Subcontinent', '70', 'Spleen', NULL, 'Published', 'KALA-AZAR MEDICAL RESEARCH CENTER, RAMBAG ROAD , MUZAFFARPUR,  BIHAR -842001, INDIA ', '75', '2000', 'http://www.ncbi.nlm.nih.gov/pubmed/10897369', 'Sundar S, Gupta LB, Rastogi V, Agrawal G, Murray HW.', '10897369', 'Short-course, cost-effective drugs with amphotericin B-fat emulsion cures visceral leishmaniasis.', 'Pentavalent Antimonial'

如您所见,最后一个值仅由列表中的第一种药物

组成

1 个答案:

答案 0 :(得分:0)

我认为你希望你的观点看起来像这样

create view your_view
as
select s.*, d.* --explicit name that stuff
from        Location l
inner join  Study s on l.id = s.location_id
inner join  Study_Drugs sd on s.id = sd.study_id
inner join  Drugs d on d.id = sd.drugs_id
inner join  Publications p on s.id = p.study_id;


select * from your_view where study_id = 1; -- whatever id

我不确定你想要的出版物是什么。 请使用带有“内部联接”的“新”符号,而不是您使用的“where”-clause。