1

我有以下查询:

SELECT 
  IF(COUNT(*) > 0, COUNT(*), '0') AS Found, 
  IF(NWLat, NWLat, '0')           AS NWLat, 
  IF(NWLon, NWLon, '0')           AS NWLon, 
  IF(SELat, SELat, '0')           AS SELat, 
  IF(SELon, SELon, '0')           AS SELon 
FROM s 
WHERE s.ci = '4' 
  AND s.snf = 'Ch'
GROUP BY s.sid 

现在它返回匹配查询的行。但是,当没有任何内容匹配时,它不会返回任何内容。如果什么也没找到,我怎样才能让它返回“Found: 0, NWLat: 0, NWLon: 0, SELat: 0, SELon: 0”?

4

3 回答 3

1

最好不要在 MySQL 中这样做。SQL 与此无关。如果您的查询未返回任何记录,则从您的前端应用程序中,您可以轻松打印 0。

但是,如果您需要以任何方式执行此操作,您可以执行以下操作:

SELECT 
  IF(COUNT(*) > 0, COUNT(*), '0') AS Found, 
  IF(NWLat, NWLat, '0')           AS NWLat, 
  IF(NWLon, NWLon, '0')           AS NWLon, 
  IF(SELat, SELat, '0')           AS SELat, 
  IF(SELon, SELon, '0')           AS SELon 
FROM s 
WHERE s.ci = '4' 
  AND s.snf = 'Ch'
GROUP BY s.sid 
UNION ALL
SELECT
  '0' AS Found, 
  '0' AS NWLat, 
  '0' AS NWLon, 
  '0' AS SELat, 
  '0' AS SELon 
FROM s 
WHERE NOT EXISTS(
    SELECT 
      IF(COUNT(*) > 0, COUNT(*), '0') AS Found, 
      IF(NWLat, NWLat, '0')           AS NWLat, 
      IF(NWLon, NWLon, '0')           AS NWLon, 
      IF(SELat, SELat, '0')           AS SELat, 
      IF(SELon, SELon, '0')           AS SELon 
    FROM s 
    WHERE s.ci = '4' 
    AND s.snf = 'Ch'
    GROUP BY s.sid
);

演示:

于 2013-01-13T08:00:57.980 回答
0

仅供参考,如果你真的有一个COUNT(*)0,这意味着该组没有行,所以结果中永远不会有一行。你IF(COUNT(*) > 0, COUNT(*), '0')不会对你有任何好处,因为不会有任何一行显示 0。

至于其他如果,我怀疑你想要这样的东西:等等。
SELECT (case when NWLat is null then 0 else NWLat end)
. . .
GROUP BY sid, (case when NWLat is null then 0 else NWLat end),

这将允许那些被包含在组中,并允许 0 显示为一个组。

于 2013-01-13T07:39:48.390 回答
0

对于你最后的评论,你想试试这个吗?在这里,您不必全部计算以确定您是否有根据条件需要的记录。

SELECT     
case when NWLat is null then 0 else NWLat end AS NWLat, 
case when NWLon is null then 0 else NWLon end AS NWLon,
case when SELat is null then 0 else SELat end AS SELat,
case when SELon is null then 0 else SELon end AS SELon
FROM S
where NOT EXISTS(SELECT 1
             FROM s
             WHERE ci = 4 and snf = 'Ch')
GROUP BY sid, NWLon, SELat, SELon;
于 2013-01-13T07:41:38.693 回答