Select A.a_id from
(Select distinct a_id from table_b where name_b = '张三' )A
inner join (Select distinct a_id from table_b where name_b = '李四')B
on A.a_id=B.a_id
有了a_id这东西,其他都好办了。
结果应该是正确的,不过张三 、李四这些条件是动态的,个数也是动态的,程序中怎么组装这个sql呢
@什麼江湖: 组装是另外一个问题吧,想想总能想出来的。
你自己想吧,SQL问题要完成一般都不难,只要思路清晰。(当然性能优化是另外一回事了)
我很少在程序中写SQL语句,LINQ好多年了。
select id,name_a from table_a inner join table_b on table_a.id=table_b.a_id
where name_b = '张三' or name_b = '李四'
group by id,name_a
select id ,name_a from table_a where exists (select 1 from table_b where a_id = id and (name_b = '张三' or name_b = '李四'))
where name_b = '张三' and name_b = '李四' 这个肯定不对啊
@什麼江湖: 对对对。应该是or,栽了。
@长蘑菇星人: 哈哈哈,这个题是送命题。
@长蘑菇星人: 您这是写了两条sql是吗?如果子表中同时存在两条 张三 或两条 李四 的话,结果又不对了
@什麼江湖: 您说的对,我刚百度学习的sql
@什麼江湖:
select id ,name_a from table_a where exists (select 1 from table_b where a_id = id and name_b = '张三' ) and exists (select 1 from table_b where a_id = id and name_b = '李4' )
@什麼江湖:
select * from table_a where
(select count(name_b) from (select name_b from table_b where name_b in ('张三','李四') and a_id = table_a.id
group by name_b ) as c) = 2
SELECT * FROM table_a a WHERE (SELECT COUNT(id) FROM table_b b WHERE a.id = b.a_id and (b.name_b = '张三' or b.name_b = '李四') =2。
很没有效率的语句,应该能用。懒得去连表运算了。
这个有问题吧 ,如果一个主表下存在两个“张三”的话,不就出问题了吗
@什麼江湖: 如果是只要求存在,不限制数量,当然就得改改。一个子查询搞不定,那就两个。
select table_a.id,table_a.name_a,table_b.name_b from table_a ,table_b where table_b.a_id=table_a.id and (name_b='张三' or name_b='李四')
这个肯定不对的
@什麼江湖: 这个是sqlserver,mysql的写法不清楚
sql中还可以这样写:SELECT a.id,b.name_b FROM dbo.Table_a AS a,dbo.Table_b AS b
WHERE b.a_id=a.id and b.name_b in('张三','李四')
都是不认真看题的啊。
select * from table_a where id in (select a_id from table_b b1 left join table_b b2 on b1.a_id = b2.a_id where b1.name='张三' and b2.name='李四')
SELECT * FROM table_a FROM id IN(SELECT a_id FROM table_b WHERE name_b='张三' INTERSECT SELECT a_id FROM table_b WHERE name_b='李四')
我认真看题目了,啊哈,应该可以
@什麼江湖 这是ms sqlservice 中的写法, 不知道在mysql中是否可行
select * from table_a where id in (select a_id from table_b where name_b="张三" or name_b="李四")
SELECT id ,name_a FROM table_a
WHERE id IN (
SELECT a_id FROM table_b
WHERE name_b IN ('张三','李四')
)