开发者

Selecting only rows which are associatied to a row in some other particular table

table1:
columns: id, name

table2:
columns: id, name

assoc_table1_table2:
columns: id_table1, id_table2

I need to select all rows from table1 where at least one row in table2 is associated with this row.

What would be an efficient way to do it? Or, more correct in some way?

I'm thinking of:

SELECT DISTINCT t.id, t.name
FROM table1 t
JOIN a开发者_开发知识库ssoc_table1_table2 a ON t.id=a.id_table1;

or:

SELECT id, name
FROM table1 t WHERE EXISTS (
    SELECT *
    FROM assoc_table1_table2 a
    WHERE t.id=a.id_table1
);

Any ideas on what of the above is generally faster?

(the obvious indices are in place)


Neither.

I'd recommend using a "WHERE EXISTS" as it will give the optimizer more freedom.

Using "WHERE COUNT(*)" or DISTINCT will force a full table scan to compute.

You only want to know whether at least 1 row exists, for example, on a billion row table. "WHERE EXISTS" can be satisfied as soon as the db finds the first row. On databases with reasonable optimizers, you should find it works well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜