繁体   English   中英

mysql在where子句中从同一表中选择两次具有不同日期的列

[英]mysql Select one column twice from the same table with different dates in the where clause

我有两个SQL查询,我想将它们合并到一个SQL查询中并显示在一张表上:

SELECT subname,subscribers as sub1 FROM reports_subreport where  country ='1' and mp='0' and date ='2013-10-15' and NOT(subname LIKE '%Test%')  order by site,subname


SELECT subscribers as sub2 FROM reports_subreport where country ='1' and mp='0' and date ='2013-10-08' and NOT(subname LIKE '%Test%')  order by site,subname

应该在表中显示如下内容:

子名称 sub1 sub2

ENT 222202

您能帮我吗,因为我是mysql和php的新手吗?

已经给出了一些更好,更专业的答案,但这是最好的了解情况的答案。

SELECT subname, 

    (SELECT subscribers 
     FROM reports_subreport 
     WHERE country ='1' AND mp='0' 
     AND date ='2013-10-15' 
     AND NOT(subname LIKE '%Test%') 
     ORDER BY site,subname LIMIT 1) AS sub1,

    (SELECT subscribers 
     FROM reports_subreport 
     WHERE country ='1' AND mp='0' 
     AND date ='2013-10-08' 
     AND NOT(subname LIKE '%Test%') 
     ORDER BY site,subname LIMIT 1) AS sub2,

FROM reports_subreport WHERE country ='1' AND mp='0' 
AND date ='2013-10-15' AND NOT(subname LIKE '%Test%') 
ORDER BY site,subname

让我们知道这是否有效。

SELECT `subname`, CASE WHEN `date`='2013-10-15' THEN `subscribers` ELSE 'NONE' `s1` , CASE WHEN `date`='2013-10-08' THEN `subscribers` ELSE 'NONE' `s2`
WHERE `country` ='1' AND `mp`='0' AND NOT(`subname` LIKE '%Test%') ORDER BY `site`,`subname`

您可以在列选择中使用简单的IF

SELECT
  subname,
  if(date ='2013-10-15', subscribers) as sub1,
  if(date ='2013-10-08', subscribers) as sub2
FROM reports_subreport
WHERE country ='1' and mp='0' and date IN ('2013-10-15','2013-10-08') and NOT(subname LIKE '%Test%')  order by site,subname

暂无
暂无

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

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