0

我想在 MySQL 查询中使用 if 语句来查询SELECT数据库中的所有信息,如果它返回 true,或者返回COUNT名为aid​​ .

伪代码:

IF (COUNT(`AID`) > 0) {
  SELECT * FROM `a_votes` WHERE `aid` = '1'
} ELSE {
  RETURN 'No Rows'
}

请你能告诉我我该怎么做吗?

编辑 - -

我尝试了以下查询,但收到错误消息Operand should contain 1 column(s)

SELECT IF( (

SELECT COUNT( aid ) AS  `count` 
FROM  `a_votes` 
WHERE  `aid` =1 ) =0,  'true', (

    SELECT * 
    FROM  `a_votes` 
    WHERE  `aid` =1
  )

) AS message
4

2 回答 2

1
SELECT * FROM (
    SELECT COUNT(*) as COUNT FROM a_votes WHERE aid = '1'
) x WHERE COUNT > 0;

如果没有匹配的行,一个简单的将返回一个用于计数COUNT(*))的单行。0将常规COUNT(*)查询包装在消除该条件的外部查询中将不返回任何行。

编辑:

感谢@bisiclop,这是一个更好的解决方案:

SELECT COUNT(*) as COUNT
FROM a_votes
WHERE aid = '1'
HAVING COUNT(*) > 0;
于 2012-06-16T19:00:29.020 回答
0

如果我想将您的伪代码转录为 SQL,这将是结果,但我认为它不必要地复杂,所以它只是一个演示:

/* this query might return zero rows, so beware */
SELECT
  (SELECT COUNT(`aid`) > 0 FROM `a_votes`) AS the_count,
  the_row.*
FROM
  (SELECT * FROM `a_votes` WHERE `aid` = '1') AS the_row

同样 using LEFT JOIN,它必须至少返回一行:

SELECT *
/* count will create exactly 1 row */
FROM      (SELECT COUNT(`aid`) > 0 FROM `a_votes`)    AS the_count
/* this is allowed to return 0,1,...N rows */
LEFT JOIN (SELECT * FROM `a_votes` WHERE `aid` = '1') AS the_row
于 2012-06-16T18:59:37.503 回答