I am attempting to find all sets of two records in my "story" table such that the two records do not connect to any of the same records of a certain type in "character" (via "participant", the bridge entity). Here is the query as I've written it:

SELECT str1._id, str2._id
FROM story AS str1, story AS str2
WHERE str1._id < str2._id
AND (SELECT COUNT(chr_id) FROM
    (SELECT chr_id
    FROM participant
    WHERE isparent = 0
    AND str_id = str1._id
    INTERSECT
    SELECT chr_id
    FROM participant
    WHERE isparent = 0
    AND str_id = str2._id)) = 0;

The innermost query, and the counting query around it, function as expected when used on their own with str1._id and str2._id replaced with actual values, but the whole query all together seems to yield TRUE for the final condition in cases where it should not. This makes me suspect that the issue is something to do with the aliasing, but I'm not sure what to change to fix this.

EDIT: Here's the sample data in the participant table that I've been using to test

str_id  chr_id  isparent
     1       1         1
     1       2         1
     1       3         0
     2       1         1
     2       3         0
     3       4         1
     3       3         1
     3       5         0
     3       6         0
     3       7         0

Here's the output the query gives

_id  _id
  1    2
  1    3
  2    3

And here's the output I expected

_id  _id
  1    3
  2    3
有帮助吗?

解决方案

I've simplified the query slightly and it now does what it was meant to. Here's the new query:

SELECT str1._id, str2._id
FROM story AS str1, story AS str2
WHERE str1._id < str2._id
AND (SELECT chr_id
    FROM participant
    WHERE isparent = 0
    AND str_id = str1._id
    INTERSECT
    SELECT chr_id
    FROM participant
    WHERE isparent = 0
    AND str_id = str2._id) IS NULL;

The mystery stands, however, of why the original query did not work.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top