比较表中不同行的相同列

时间:2013-11-21 23:52:15

标签: php mysql sql inner-join

我的MySQL表格中有以下格式的表格:

 |Result|month|Name|
 |   1  | Nov |  x | 
 |   1  | Nov |  y | 
 |   1  | Nov |  z | 
 |   2  | Dec |  x | 
 |   2  | Dec |  y | 
 |   1  | Dec |  z | 

我正在尝试获取名称的计数,其中11月的结果与dec的结果不同。对于上面的示例,它是2.我尝试了以下查询,但我似乎没有按预期得到输出:

$query =  SELECT A.Result as t1,B.Result as t2 from MonthlyState A INNER JOIN MonthlyState B ON A.Result = B.Result WHERE A.month = 'Nov' AND B.month = 'Dec'


$result=mysql_query($query);


$count1 = 0;
$count2 = 0;

while($r = mysql_fetch_assoc($result)){

  if ((string)$r['t1'] == (string)$r['t2']  ) {
        $count1 = $count1 + 1;

  }else{
        $count2 = $count2 + 1; 
  }

} 

对此有何帮助?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT A.Result as t1,B.Result
FROM MonthlyState A
INNER JOIN MonthlyState B ON A.name = B.name
WHERE A.month = 'Nov'
  AND B.month = 'Dec'
  AND b.result != a.result

如果你想直接获得COUNT,你可以这样做:

SELECT COUNT(*)
FROM MonthlyState A
INNER JOIN MonthlyState B ON A.name = B.name
WHERE A.month = 'Nov'
  AND B.month = 'Dec'
  AND b.result != a.result;

sqlfiddle demo

答案 1 :(得分:1)

SELECT
  name
FROM MonthlyState
WHERE month IN ('Nov','Dec')
GROUP BY name
HAVING COUNT(DISTINCT Result) > 1