需要sql查询以下的scenarioa

时间:2017-09-15 06:00:53

标签: mysql sql oracle

Car      Owner

'honda','nepolian'
'benz','nepolian'
'nissan','nepolian'
'lexus','sivaji'
'honda','sivaji'
'benz','sivaji'
'nissan','sivaji'
'landrover','kumar'
'kiamotors','kumar'
'honda','kumar'
'ferrari','vivek'
'suziki','vivek'

我想选择拥有nepolian拥有的所有汽车的车主?

请帮我解决这个问题!

3 个答案:

答案 0 :(得分:1)

不知道为什么你要将这个标记为mysql和oracle,但是这里是如何在mysql中(未经测试):

select owner
from yourtable
where car in (select car from yourtable where owner='nepolian')
and owner <> 'nepolian'
group by owner
having group_concat(car order by car)=(select group_concat(car order by car) from yourtable where owner='nepolian');

如果一个人可以拥有多辆同一辆车并且您不想要求每辆车的数量相同,请稍微改变一下:

having group_concat(distinct car order by car)=(select group_concat(distinct car order by car) from yourtable where owner='nepolian');

答案 1 :(得分:0)

您的意思是说您希望Cars列中的所有车辆与Owner列中的所有者等于nepolian吗?在一张桌子里?

除非它是别的东西(我希望更复杂),你应该能够这样做:

SELECT car
FROM *name of table*
WHERE owner = 'nepolian';

答案 2 :(得分:0)

select t.owner from (
  select count(t1.car) as car_count, t1.owner from tableName t1
  join tableName t2 on t2.car = t1.car
  where t2.owner = 'nepolian' and t1.owner <> 'nepolian'
  group by t1.owner )
t where t.car_count = (
  select tmp.car_count from (
         select count(car) as car_count, owner from tableName
         where owner = 'nepolian' group by owner
  ) tmp
)

也许对你有帮助!在mysql中执行即可!如果上面的sql是可行的,并且它不是很慢,请给我一个消息!