我遇到了麻烦,需要一些帮助才能找到正确的SQL查询。到目前为止,这是我的代码:
SELECT firstname, lastname, date_of_birth
FROM `data`
WHERE firstname IN (SELECT firstname
FROM `data`
WHERE diagnosis_location = 'Mayo')
AND lastname IN (SELECT lastname
FROM `data`
WHERE diagnosis_location = 'Mayo')
AND date_of_birth IN (SELECT date_of_birth
FROM `data`
WHERE diagnosis_location = 'Mayo')
AND firstname IN (SELECT firstname
FROM `data`
WHERE diagnosis_location = 'Lahey')
AND lastname IN (SELECT lastname
FROM `data`
WHERE diagnosis_location = 'Lahey')
AND date_of_birth IN (SELECT date_of_birth
FROM `data`
WHERE diagnosis_location = 'Lahey')
是的,它是一个查询的怪物,可能并不是那么有效。但我要做的只是返回在'Mayo'位置和'Lahey'位置诊断出的所有患者的名字,姓氏和出生日期。此查询确实返回了这些患者,但它返回了相同确切数据的多行。
我怎么能限制它,所以修剪出相同结果的重复?
答案 0 :(得分:2)
使用:
SELECT firstname, lastname, date_of_birth
FROM `data`
WHERE diagnosis_location IN ('Mayo', 'Lahey')
GROUP BY firstname, lastname, date_of_birth
HAVING COUNT(DISTINCT diagnosis_location) = 2
答案 1 :(得分:1)
你应该考虑使用EXISTS来做这样的事情
也许尝试像
这样的东西SELECT DISTINCT
firstname,
lastname,
date_of_birth
FROM `data` d
WHERE EXISTS (
SELECT *
FROM `data` dE
WHERE d.firstname = dE.firstname
AND d.lastname = dE.lastname
AND d.date_of_birth = dE.date_of_birth
AND diagnosis_location ='Mayo'
)
AND EXISTS (
SELECT *
FROM `data` dE
WHERE d.firstname = dE.firstname
AND d.lastname = dE.lastname
AND d.date_of_birth = dE.date_of_birth
AND diagnosis_location = 'Lahey'
)
答案 2 :(得分:0)
试试这个:
select `firstname`, `lastname`, `date_of_birth`
from `data`
where `diagnosis_location`='Mayo' or `diagnosis_location`='Lahey'
group by `firstname`, `lastname`, `date_of_birth`
having count(`diagnosis_location`) = 2