1

I think i have a somewhat simple problem but due to my lack of experience in DB modelling and SQL i'm unable to get the right solution, i can draw the basic concept but i'm having a hard time to implement a solution

Let's say i have some sets A,B and C.

A is inside B

B is inside C

A is the set of the 10 objects with greatest value inside B set

B is the set of all values greater than 100

C is the set of all values greater than 50

enter image description here

that's the easy part,

Now i need to get 50 objects with the greatst value from C that are not inside A How would i translate that problem to the SQL language, or what commands, tools or design patterns should i use to solve this problem?

I'm not sure if I was clear enough, again sorry if the problem is too trivial for some, but i'm trying to learn more about SQL and designs.

I'm looking for a general solution that it's not bound by a framework or OS

Thanks for any help

4

3 回答 3

2

让我假设您有一个t带有value列的表,并且标签“A”、“B”和“C”是基于这些的。

select t.*
from t left outer join
     (select value
      from t
      where value >= 100
      order by value desc
      limit 1
     ) A
     on t.value = A.value
where t.value >= 50 and A.value is null
order by value desc
limit 50;

的使用limit是特定于数据库的。它可能在toprownumwhere子句中或其他内容中,具体取决于数据库。

编辑:

如果集合足够大,您可以这样做:

select t.*
from t
where value >= 50 and value < 100
order by value desc
limit 50;
于 2013-09-13T19:41:40.893 回答
0

可能这个查询会有所帮助:

select Col1,Max(Col2) from
(select col1, col2 from TableC
Except
Select col1, col2 from TableA)as A
Group By Col1

这里内部查询只会选择表 A 中的记录,而不是表 C 中的记录,然后外部查询将取这些记录中的最大值。

于 2013-09-13T19:40:49.577 回答
0

嗨,我不确定我是否正确理解了您的问题。如果我考虑 A、B 和 C 您的 SQL 表并假设它们之间存在某种关系,那么您可以编写类似的查询

从 C 中选择 C.*,其中 C.ID 不在

(从 B 中选择 B.ID 在 B.ID = A.ID 上加入 A)

子查询(第二行)为您提供 B 和 A 之间共有的所有对象(本质上是 A)。

同样,我不确定这是否是您正在寻找的,如果您可以在这里分享您的真实生活场景将会很有帮助。

关于集合论和 SQL 的理解请参考下面的文章

http://seanmehan.globat.com/blog/2011/12/20/set-theory-and-sql-concepts/

于 2013-09-13T19:47:57.340 回答