SQL select from data in query where this data is not already in the database?

前端 未结 5 1102
日久生厌
日久生厌 2021-01-20 22:00

I want to check my database for records that I already have recorded before making a web service call.

Here is what I imagine the query to look like, I just can\'t

5条回答
  •  旧时难觅i
    2021-01-20 22:33

    To confirm I've understood correctly, you want to pass in a list of numbers and see which of those numbers isn't present in the existing table? In effect:

    SELECT Item
    FROM IDList I
        LEFT JOIN TABLE T ON I.Item=T.ID
    WHERE T.ID IS NULL
    

    You look like you're OK with building this query on the fly, in which case you can do this with a numbers / tally table by changing the above into

    SELECT Number
    FROM (SELECT Number FROM Numbers WHERE Number IN (1,2,3,4)) I
        LEFT JOIN TABLE T ON I.Number=T.ID
    WHERE T.ID IS NULL
    

    This is relatively prone to SQL Injection attacks though because of the way the query is being built. It'd be better if you could pass in '1,2,3,4' as a string and split it into sections to generate your numbers list to join against in a safer way - for an example of how to do that, see http://www.sqlteam.com/article/parsing-csv-values-into-multiple-rows

    All of this presumes you've got a numbers / tally table in your database, but they're sufficiently useful in general that I'd strongly recommend you do.

提交回复
热议问题