MySQL Query不使用此查询返回所有行

时间:2013-01-13 07:19:49

标签: mysql row

我有以下查询:

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”?

3 个答案:

答案 0 :(得分: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
);

<强>演示:

答案 1 :(得分:0)

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

至于其他ifs,我怀疑你想要这样的东西:
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作为一个组显示。

答案 2 :(得分: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;