我有一个存储有关事务的信息的表,其中KeyInfo列并不总是可用,但是为同一事务中的所有条目生成了GUID。
GUID | KeyInfo | Message
================================================
123456 | No Info | Sample message 1
123456 | No Info | Sample message 2
123456 | Test-1 | Sample message 3
123456 | No Info | Sample message 4
321654 | No Info | Sample message 5
321654 | No Info | Sample message 6
321654 | Test-2 | Sample message 7
321654 | No Info | Sample message 8
789456 | Test-1 | Sample message 1
789456 | No Info | Sample message 2
789456 | Test-1 | Sample message 3
789456 | No Info | Sample message 4
目前我可以进行这样的搜索:
select GUID, KeyInfo, Message from MyTable where KeyInfo = 'Test-1'
这只返回两行
GUID | KeyInfo | Message
================================================
123456 | Test-1 | Sample message 3
789456 | Test-1 | Sample message 3
但是我需要一个返回属于一个事务的所有行的查询(相同的GUID),类似这样的
123456 | Test-1 | Sample message 1
123456 | Test-1 | Sample message 2
123456 | Test-1 | Sample message 3
123456 | Test-1 | Sample message 4
789456 | Test-1 | Sample message 1
789456 | Test-1 | Sample message 2
789456 | Test-1 | Sample message 3
789456 | Test-1 | Sample message 4
关于如何实现这一目标的任何想法?
答案 0 :(得分:2)
这是一种方法......
SELECT *
FROM MyTable
WHERE GUID IN (
SELECT GUID
FROM MyTable
WHERE KeyInfo = 'Test-1'
)
与JOIN不同,您不必担心KeyInfo = 'Test-1'
行是否有多行。
答案 1 :(得分:1)
select GUID, KeyInfo, Message from MyTable where GUID
IN(SELECT GUID from MyTable Where KeyInfo = 'Test-1')
我认为abover查询会有更好的表现
答案 2 :(得分:0)
是的,您可以使用自联接获取数据,如下所示:
select
mt1.GUID, mt1.KeyInfo, mt1.Message
from MyTable mt1, MyTable mt2
where mt1.GUID = mt2.GUID
and mt2.KeyInfo = 'Test-1'