tags:

views:

44

answers:

2

I have two tables A and B where there is one-to-many relationship.

Now I want some records from A and with this existence field that shows if B has any matching records. I don't want to use the count function as B has too many records that delays SQL execution. Either I don't want to use proprietary keywords like rownum of Oracle like below, as I need as much compatibility as possible.

select A.*, (
    select 1 from B where ref_column = A.ref_column and rownum = 1
) existence
...
A: 

Use an EXISTS clause. If the foreign key in B is indexed, performance should not be an issue.

SELECT *
FROM a
WHERE EXISTS (SELECT 1 FROM b WHERE b.a_id = a.id)
cletus
Your code doesn't return records of A which don't have matching records in B.
DylanYi
+1  A: 

You would use left join + count anyway, select statement in select list can be executed multiple times while join will be done only once.

Also you can consider EXISTS:

select A.*, case when exists (
    select 1 from B where ref_column = A.ref_column and rownum = 1
) then 1 else 0 end
Andrew Bezzub
+1: I would add the name(alias) to that column. I do not think that `rownum` is ANSI SQL. In SQL Server it would be `SELECT TOP 1` instead, in MySQL it would be `LIMIT 1`. To get really `ANSI SQL` implementation, `LEFT JOIN` is required, where the `COUNT(*)` would be replaced with `CASE WHEN COUNT(*)...`
van