我有两张桌子。一个是TblPeople(ID(PK),名字,姓氏,Embo ..)和其他是TBLembolization(EmbolizationID(PK),PeopleID(FK),EmbolizationDate ,.。
以下是我使用姓名搜索栓塞日期的人的查询...
SELECT tblpeople.FirstName,details.peopleID,details.embolizationDate FROM tblpeople
LEFT JOIN tblembolizations AS details ON tblpeople.ID=details.peopleID
WHERE tblpeople.Embo = 1 and concat(FirstName,' ',LastName) like '%alina%'
UNION
SELECT tblpeople.FirstName,details.peopleID,details.embolizationDate FROM tblpeople
LEFT JOIN tblembolizations AS details ON tblpeople.ID=details.peopleID
WHERE tblpeople.Embo != 1 and concat(' ',FirstName,' ',LastName,' ') like '%alina%'
结果是:
............Result .......................
FirstName |peopleID|embolizationDate
Alina |16,459 |2017-27-03
Alina | 16,459 |2017-24-03
Alina D. | 14,499 |2017-27-09
======================================
你可以看到alina有多个记录,因为她在两个日期进行了栓塞。我希望它在单个记录中,如果有人已经超过1次栓塞,所以我想要它像这样的东西
............Result .......................
FirstName |peopleID|embolizationDate|2ndembolization
Alina |16,459 |2017-27-03 |2017-24-03
Alina D. | 14,499 |2017-27-09
======================================
是否有可能在单个记录中得到答案,如果有人多次进行栓塞,并且某个人只进行了一次栓塞而不是记录以正确的方式显示。 感谢
答案 0 :(得分:2)
我不明白你使用UNION
的原因。这似乎是一个简单的聚合。
将值放在单独的列中非常棘手。将它们放在分隔的字符串中更容易。也许这就是你想要的:
SELECT p.FirstName, p.ID, GROUP_CONCAT(d.embolizationDate) as dates
FROM tblpeople p LEFT JOIN
tblembolizations details
ON p.ID = details.peopleID
WHERE pconcat(FirstName,' ',LastName) like '%alina%'
GROUP BY p.FirstName, p.ID;