如何相交2个子查询

问题描述 投票:0回答:2

您好,我想将 2 个长查询相互交叉,但我发现只能交叉简单查询。有可能得到这样的东西吗?

SELECT id, name as antibodyName 
FROM Antibodies 
WHERE id IN (
           (SELECT id FROM Antibodies WHERE name LIKE ?
                   UNION ALL
            SELECT antiId FROM AssignedColors WHERE name LIKE ?
                   UNION ALL
            SELECT antiId FROM AssignedReactivities WHERE name LIKE ?)
         INTERSECT
           (SELECT id FROM Antibodies WHERE name LIKE ?
                   UNION ALL
            SELECT antiId FROM AssignedColors WHERE name LIKE ?
                   UNION ALL
            SELECT antiId FROM AssignedReactivities WHERE name LIKE ?)
)
AND dateOfCreation >= ? AND dateOfCreation <= ?
ORDER BY dateOfCreation DESC LIMIT ? OFFSET ?;

实际上我想获得其他查询的并集的交集。

sql sqlite node-sqlite3
2个回答
1
投票

您必须为每组联合查询使用

SELECT
语句:

SELECT id, name as antibodyName 
FROM Antibodies 
WHERE id IN (
  SELECT id FROM
  (
    SELECT id FROM Antibodies WHERE name LIKE ?
    UNION all
    SELECT antiId FROM AssignedColors WHERE name LIKE ?
    UNION all
    SELECT antiId FROM AssignedReactivities WHERE name LIKE ?
  )
  INTERSECT
  SELECT id FROM
  (
    SELECT id FROM Antibodies WHERE name LIKE ?
    UNION all
    SELECT antiId FROM AssignedColors WHERE name LIKE ?
    UNION all
    SELECT antiId FROM AssignedReactivities WHERE name LIKE ?
  )
) AND dateOfCreation >= ? AND dateOfCreation <= ?
ORDER BY dateOfCreation DESC LIMIT ? OFFSET?;

1
投票

如果我正确理解你的问题,内部连接将有助于最有效地解决问题。里面的INSERSECT可以改成下面的代码,外面的SELECT可以保持不变。

(SELECT id FROM Antibodies WHERE name LIKE ?
UNION all
SELECT antiId FROM AssignedColors WHERE name LIKE ?
UNION all
SELECT antiId FROM AssignedReactivities WHERE name LIKE ?) A
JOIN
(SELECT id FROM Antibodies WHERE name LIKE ?
UNION all
SELECT antiId FROM AssignedColors WHERE name LIKE ?
UNION all
SELECT antiId FROM AssignedReactivities WHERE name LIKE ?) B
ON A.id = B.id

© www.soinside.com 2019 - 2024. All rights reserved.