简体   繁体   English

我可以使用SQL同时计算行数和获取列值吗?

[英]Can I count rows and get a column value at the same time with SQL?

I'm using a SELECT COUNT(*) in order to verify that a user exists with PHP PDO and MySQL. 我正在使用SELECT COUNT(*)来验证用户是否存在PHP PDO和MySQL。 I'd also like to get a specific column value. 我还想获得一个特定的列值。 There is only ever one value/row or no value/row per user. 每个用户只有一个价值/行,或者没有价值/行。

I'm trying to do something like this: 我正在尝试做这样的事情:

$stmt = $link->prepare('SELECT COUNT(*) AND column FROM table WHERE user=:user');

What I'm hoping to get back is, 1, and the column value. 我希望得到的是1和列值。 Where I can then bind the column value to a variable. 然后,我可以在其中将列值绑定到变量。

If not, I'll have to first do the SELECT COUNT(*) then do another query to get the column name after verifying that the user and this column exists from the SELECT COUNT(*) query. 如果没有,我将必须先执行SELECT COUNT(*)然后在验证用户和SELECT COUNT(*)查询中的此列是否存在之后,再执行另一个查询以获取列名。

You just need to think a little. 您只需要考虑一下。

"count(*)" is not a special method "to verify that a user exists". “ count(*)”不是“验证用户存在”的特殊方法。 It's just a query where you select count because you just have no idea what to select else. 这只是选择计数的查询,因为您根本不知道选择其他什么。

But as long as you have a column to select, you don't need no counts anymore. 但是,只要您有一列可供选择,就不需要计数了。

Therefore, just select your value, and as long as you are getting it, you can tell that a user exists 因此,只需选择您的值,只要您能获得它,就可以说出一个用户存在

$stmt = $link->prepare('SELECT column FROM table WHERE user=:user');
$stmt->execute([$user]);
$col = $stmt->fetchColumn();

if ($col) {
    // user exists
    $something = $col; // use $col as you wanted
}

While selecting count() and a column without a group by operator is a tricky query, and you should avoid it in general. 在选择count()和没有group by运算符的列时,这是一个棘手的查询,通常应避免使用它。

SELECT count(*), column FROM table where user=:user

It's what you want no ? 这是你想要的吗?

Otherwise you can count the number of result in php 否则,您可以在php中计算结果数

$pdo = new PDO('mysql:host=XXX.fr.mysql;dbname=YYYY', 'ZZZ', 'TTT', $pdo_options);

    $response = $pdo->query('SELECT column FROM table');
    $count = 0;
    while ($data = $response->fetch())
    {
        $count++;
    }
    $reponse->closeCursor(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM