What makes the big difference between a backtick and an apostrophe?

前端 未结 3 1946
日久生厌
日久生厌 2020-12-19 03:20

What is the reason that the following two queries give wildly different results?

MariaDB [mydatabase]> SELECT COUNT(DISTINCT(`price`)) FROM `products`; --         


        
3条回答
  •  眼角桃花
    2020-12-19 03:26

    'price' (apostrophes or quotes) is a string. It never changes, so the count is always 1.

    `price` (backtics) refers to the column price. So it could be more than 1.

    The inner parentheses are irrelevant. COUNT(DISTINCT price) is the same as your backtic version.

    • SELECT COUNT(*) FROM tbl WHERE ... is a common way to ask how many rows.
    • SELECT foo, COUNT(*) FROM tbl GROUP BY foo is a common way to ask how many rows for each distinct value of foo.
    • SELECT foo, COUNT(foo) FROM tbl GROUP BY foo is the same as above, but does not count rows where foo IS NULL.

    SELECT DISTINCT ... GROUP BY ... is a nonsense statement. Either use DISTINCT or use GROUP BY.

提交回复
热议问题