加入sql server给我更多行

时间:2015-05-19 05:35:02

标签: sql sql-server-2012

我有两张桌子

1. User

    id      language            program  status
    1       English/Spanish     CF/CA       1
    2       English             C           1
    3       Spanish             CF          1
    4       Greek               CA          1

2. Entry

   language             program
    English             CF
    English             C
    Spanish             CF
    Spanish             C

我的要求是从User表中获取language and program row in Entry table和状态= 1

的详细信息
    eg:- User ID 1 has language English/Spanish and Program CF and 
User id 2 has language English and Program C and user 3 has 
spanish and CF so only 3 rows will be retrieve

我正在使用以下查询

select u.*
from user u inner join
Entry e
on( u.language like '%'+e.language+'%'
and u.program like '%'+e.program+'%')
where [status] = 1

我的结果低于结果。我知道加入一些pblm我无法修复。 请帮忙

User id     language           program     Status
1           English/Spanish    CF/CA        1
1           English/Spanish    CF/CA        1
1           English/Spanish    CF/CA        1
1           English/Spanish    CF/CA        1
2           English            C            1
3           Spanish            CF           1
3           Spanish            CF           1

2 个答案:

答案 0 :(得分:4)

一种解决方案可能是添加group by u.id, u.language, u.program, u.status 因为你只从用户表中选择数据。

但您也可以考虑重新设计表格,以便为这个问题找到更好的解决方案,例如为语言和程序创建表格。

[编辑:修正错误]

答案 1 :(得分:3)

    select u.*
from [user] u where  exists ( select 1 from 
Entry e
where (u.[language] like '%'+e.[language]+'%'
and u.program like '%'+e.program+'%')
and [status] = 1)