mysql从同一个表中选择一列,并在where子句中使用不同的日期

时间:2013-10-15 05:43:14

标签: php mysql

我有两个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 222 202

你可以帮助我,因为我刚接触mysql和php吗?

3 个答案:

答案 0 :(得分:2)

已经有一些更好,更专业的答案,但这个答案最好理解发生了什么

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

答案 1 :(得分:1)

如果有效,请告诉我们。

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`

答案 2 :(得分:1)

您可以在列选择中使用简单的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