简体   繁体   English

使用存在的WHERE返回不同的行(从表中选择1)

[英]Returning distinct rows using WHERE Exists(SELECT 1 FROM TABLE)

I've got two tables in my SQLite database with a one to many relationship between them: 我的SQLite数据库中有两个表,它们之间是一对多的关系:

CREATE TABLE Reads (
    RowID     INTEGER NOT NULL PRIMARY KEY,
    EventDate INTEGER NOT NULL,
    Plate     TEXT,
    State     TEXT
);

CREATE TABLE ExplodedPlates (
    Plate     TEXT,
    RowID     INTEGER NOT NULL,
    PRIMARY KEY (RowID, Plate)
) WITHOUT RowId;

The Reads table's Plate column contains license plates. Reads表的Plate列包含牌照。 The data may contain what we call "ambiguous license plates". 数据可能包含我们所谓的“模糊车牌”。 For example, a plate may contain "A[0OQ]C1234", where the actual second character could be a "0", an "O", or a "Q". 例如,一个牌可以包含“ A [0OQ] C1234”,其中实际的第二个字符可以是“ 0”,“ O”或“ Q”。 In this case, there are three rows in the ExplodedPlates table with the same RowID but the Plate is "A0C123", another with "AOC1234", and a third with "AQC123". 在这种情况下,ExplodedPlates表中有三行具有相同的RowID,但Plate为“ A0C123”,另一行为“ AOC1234”,第三行为“ AQC123”。

I need to join these tables and return one row for each unique RowID where the plate matches a pattern similar to the one in the example. 我需要连接这些表,并为每个唯一的RowID返回一行,在该唯一的RowID中,该板匹配与示例中的模式相似的模式。 So if the user enters "A[O0]1234" in the search box, they should get one row with the plate "A[0OQ]1234", but not 3, as well as any rows with other RowIDs that match that string. 因此,如果用户在搜索框中输入“ A [O0] 1234”,则他们应该获得带有标牌“ A [0OQ] 1234”的一行,而不是3,以及包含与该字符串匹配的其他RowID的任何行。

I've written a query using Entity Framework similar to this one: 我已经使用实体框架编写了与此查询类似的查询:

SELECT DISTINCT r.*
FROM ExplodedPlates A x
JOIN Reads AS r ON r.RowId = x.RowID
WHERE x.Plate GLOB @Plate

This works, but the query returned uses a temporary B-Tree to do the DISTINCT. 此方法有效,但返回的查询使用临时B树执行DISTINCT。 My boss wants me to get rid of the DISTINCT and use WHERE EXISTS(SELECT 1 FROM ExplodedPlates WHERE Plate GLOB @Plate) , but I don't know how to get this to work. 我的老板要我摆脱DISTINCT并使用WHERE EXISTS(SELECT 1 FROM ExplodedPlates WHERE Plate GLOB @Plate) ,但是我不知道如何WHERE EXISTS(SELECT 1 FROM ExplodedPlates WHERE Plate GLOB @Plate)工作。 I have a specific case in my database with 135 rows that match a particular pattern, but the query I'm using returns 6557 rows. 我的数据库中有一个特定案例,其中有135行与特定模式匹配,但是我正在使用的查询返回6557行。 Clearly, this is wrong. 显然,这是错误的。

How exactly can I use that WHERE clause to generate the unique list of matching reads? 我究竟该如何使用WHERE子句来生成匹配读取的唯一列表?

This may be what you want: 这可能是您想要的:

select r.*
from reads r
where exists (select 1
              from ExplodedPlates x
              where r.RowId = x.RowID and
                    x.Plate GLOB @Plate
             );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM