求SQL查找语句
我有一个表,如下:
Id, UserID, IsShared
1, 1, N
2, 1, Y
3, 2, N
4, 2, Y
5, 3, N
6, 3, Y
比如UserID是1的时候,查找,可以找到Id为:1,2,4,6
就是说,当IsShared为Y的时候,谁都可以查得到,并且可以查到UserID为自己的所有数据,无论Y/N。请问这句如何写呢?
[解决办法]
Pattern 1 楼主的情况
select * from tb where UserID=1 or IsShared='Y'
[解决办法]
use Tempdbgo--> --> if not object_id(N'Tempdb..#T') is null drop table #TGoCreate table #T([Id] int,[UserID] int,[IsShared] nvarchar(1))Insert #Tselect 1,1,N'N' union allselect 2,1,N'Y' union allselect 3,2,N'N' union allselect 4,2,N'Y' union allselect 5,3,N'N' union allselect 6,3,N'Y'GoDECLARE @userID INTSET @userid=1Select * from #T AS aWHERE UserID=@userid OR [IsShared]='Y'/*Id UserID IsShared1 1 N2 1 Y4 2 Y6 3 Y*/
[解决办法]
1:熟悉 AND OR 的用法
2:在相同关系 的地方 用括号括起来
select * from tb where UserID=1 or showid=2 or IsShared='Y'
select * from tb where UserID=1 AND showid=2 or IsShared='Y'
select * from tb where (UserID=1 AND showid=2) or IsShared='Y'
select * from tb where UserID=1 AND (showid=2 or IsShared='Y')
分别试试 再理解一下就可灵活使用