开发者

Joining a table on itself

开发者 https://www.devze.com 2023-01-05 22:51 出处:网络
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

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 column开发者_如何学运维C is not the primary key.


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'


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'
0

精彩评论

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