1

I have a table (e.g. Motherboard) that contains the value that I'm looking for (e.g. RAM)... and let said that the Motherboard has 2 fields as PK, such as: model_id and part_number... if I had the model_id and all the RAM capacity are the same I don't care about the part numbers. The query will be something like:

SELECT Top 1 ram FROM Motherboard WHERE model_id = @model_id 

Otherwise, we have to Join the table (e.g. MyMBInfo) that we stored that part_number.

SELECT Top 1 ram FROM Motherboard m
    LEFT JOIN MyMBInfo i ON SUBSTRING(i.model_id_and_other_stuff, 1, 9) = m.model_id and i.part_number = m.part_number
    WHERE model_id = @model_id 

I can always use the second query, but it seems to be a quite expensive (join, substring, etc)... I have like millions of motherboards that need to figure out that Ram value.

I want to apply the first query and if it required, apply the second one, since (in my data) the probability that has different RAM for different parts are very rare (like 1%).

If you may know how to write a query that combine this two, something like:

SELECT Top 1 ram ... WHERE .... distinct_counter > 1 and part_number in SELECT ... FROM MyMBInfo WHERE...)

Or create a helper function.

Please share it.

4

1 に答える 1

1

単純IFなものでこれはうまくいきます:

if (select count(distinct ram) from dbo.Motherboard WHERE model_id = @model_id) = 1
    select ram from dbo.Motherboard WHERE model_id = @model_id 
else 
    SELECT Top 1 ram FROM Motherboard m
            LEFT JOIN MyMBInfo i ON SUBSTRING(i.model_id_and_other_stuff, 1, 9) = m.model_id and i.part_number = m.part_number
            WHERE model_id = @model_id 

実際のクエリ実行プランは条件によって異なるため、必要なコストのみを推測する必要があります。

オフトピック:私はあなたのでの(誤)使用について@Amadanと非常に協力していSUBSTRINGますJOIN

于 2012-12-05T20:44:18.927 に答える