SQL依赖于另一个SQL

时间:2015-08-05 21:14:14

标签: sql

我有一个名为Int => Boolean的表,如下所示:

Images

ImageKey RefKey ImageParentKey Sequence -------- ------ -------------- -------- 1234570 111111 1234567 3 1234568 111111 1234567 1 1234569 111111 1234567 2 1234567 111112 1234567 0 1234571 111112 1234571 0 1234572 111112 1234571 1 1234573 111112 1234571 2 列是表格的主键 ImageKey列确定图像与哪个文件(在另一个表中)相关联 RefKey列保存与其他后续图像关联的主ImageKey的值 “序列”列确定图像在文件中的位置

我试图找到ImageParentKey = ImageParentKey AND 的所有实例,其中具有相同ImageKey的所有其他图片具有不同{ {1}}。

基本上,我需要找到属于文件的每个图像乱序且不在文件中的位置(由Sequence和RefKey列确定)。

所需的输出将是第四行:

ImageParentKey

此行符合所有条件:

  • RefKey等于其ImageKey RefKey ImageParentKey Sequence -------- ------ --------- -------- 1234567 111112 1234567 0
  • ImageKey与具有相同ImageParentKey
  • 的其他图片不匹配

这是我到目前为止所做的事情(遗憾的是,我无需做任何事情):

RefKey

非常感谢任何有关此事的帮助!

3 个答案:

答案 0 :(得分:3)

这是我的方法:

SELECT * 
FROM Images i 
WHERE 
    /* ImageKey equals its ImageParentKey */
    i.ImageKey = i.ImageParentKey
    AND 
    /* There's a RefKey that doesn't match other images with the same ImageParentKey */
    EXISTS 
    (
        SELECT * 
        FROM Images i2 
        WHERE i2.ImageParentKey = i.ImageKey AND i.RefKey <> i2.RefKey
    )

输出:

ImageKey RefKey ImageParentKey Sequence
-------- ------ -------------- -----------
1234567  111112 1234567        0

答案 1 :(得分:1)

您可以使用排除联接返回到同一个表:

SELECT i1.*
FROM Images i1
LEFT JOIN Images i2 ON i2.ImageParentKey = i1.ImageParentKey AND i2.RefKey = i1.RefKey 
     AND i2.Sequence <> i1.Sequence
WHERE i1.ImageKey = i1.ImageParentKey AND i2.ImageKey IS NULL

结果:

1234567    111112  1234567 0

Sql Fiddle

答案 2 :(得分:0)

您可以在ImageKey和ParentKey上将Images表连接到自身,以查找Children与父级不具有相同RefKey的行。下面的东西可能会起作用。您可以将其更改为具有Select Distinct PI。*如果您只想要父行

Select PI.*, CI.*
from Images PI
inner join Images CI
on PI.ImageKey=CI.ImageParentKey
and PI.RefKey<>CI.RefKey