tags:

views:

99

answers:

2

Is there a better way to write this SQL query?

SELECT *,  (SELECT TOP 1 columnB FROM mytable WHERE mytable.columnC = T1.columnC ORDER BY columnD) as firstRecordOfColumnB
FROM
    (SELECT * FROM mytable WHERE columnA = 'apple') as T1

Notice that columnC is not the primary key.

A: 

This might be better in case of performance:

SELECT
  *,
  (TOP 1 myLookupTable.columnB FROM mytable AS myLookupTable WHERE myLookupTable.keyColumn = mytable.keyColumn) as firstRecordOfColumnB
FROM
  mytable
WHERE
  columnA = 'apple'

But for the TOP 1 part I don't know any better solution.

Edit: If the keyColumn is unique, the data in firstRecordOfColumnB would be the same as in mytable.columnB. If it's not unique at least you need to sort that data to get a relevant TOP 1, example:

SELECT
  *,
  (TOP 1 myLookupTable.columnB FROM mytable AS myLookupTable WHERE myLookupTable.keyColumn = mytable.keyColumn
   ORDER BY myLookupTable.sortColumn) as firstRecordOfColumnB
FROM
  mytable
WHERE
  columnA = 'apple'
Peter Forss
thx. i didn't know that i can use AS like this:SELECT ... FROM mytable AS myLookupTable ...and yes, i'm not joining on the primary key. but the table is already sorted.
homam
You are welcome. Please mark this as the answer if you think it solved your problem :)
Peter Forss
+2  A: 

If the keyColumns is really a key column (i.e. unique), than the query can definitly be written more elegantly and efficiently...

SELECT
  *, columnB
FROM
  mytable
WHERE
  columnA = 'apple'
inflagranti
+1. I had to work out an example to notice that...
Lieven
columnB will be a part of * I guess? If you don't want columnB to be at the end you can simply write: *
Peter Forss
no sorry, it was a mistake to name it keyColumn. it is not the primary key.
homam