MySQL 检查数据库中是否存在 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/797879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:10:52  来源:igfitidea点击:

Check to see if an ID exists in a database

mysqlexistsid

提问by Ben McRae

When given an IDnumber, I want to check to see if it exists in the database. Return trueif the IDis found and if not, then return false.

当给出一个ID数字时,我想检查它是否存在于数据库中。返回true如果ID被发现,如果没有,则返回false

My knowledge of MySQL is very low, but I am assuming it would be something to do with the COUNT(*)function possibly?

我对 MySQL 的了解非常少,但我假设这可能与COUNT(*)函数有关?

回答by cgp

select id from table where id = $id

No need to get fancy. Using exists with subqueries seems likely only to generate poor performance, but I'm happy to be corrected if shown otherwise.

没必要花哨。对子查询使用exists 似乎只会产生较差的性能,但如果以其他方式显示,我很高兴得到纠正。

回答by ólafur Waage

Just to add another example.

只是添加另一个例子。

SELECT COUNT(id) FROM table WHERE id = 123

回答by ólafur Waage

SELECT ID FROM TABLE WHERE ID = 'number'; 
SELECT count(*) FROM TABLE WHERE ID = 'number'; 1 - exists, 

In your PHP or other code, you must check if one of these queries return value.

在您的 PHP 或其他代码中,您必须检查这些查询之一是否返回值。