この質問のバージョンと数時間格闘してきましたが、おそらく私が見逃しているのは小さなことだと思います.
この投稿の最初の回答に基づいたクエリがあります。
SQL でフィールド値ごとの行数を制限するにはどうすればよいですか?
これはまさにMySQL Workbenchでやりたいことですが、実行時にセッション変数を「2」に設定することはありません:
mysql_query()
PHPで。
以下は、問題を示す表「mytab」です。
+----+--------------+---------------+
| id | first_column | second_column |
+----+--------------+---------------+
| 1 | 1 | 1 |
| 2 | 1 | 4 |
| 3 | 2 | 10 |
| 4 | 3 | 4 |
| 5 | 1 | 4 |
| 6 | 2 | 5 |
| 7 | 1 | 6 |
+----+--------------+---------------+
単純化されたクエリ:
select
id, first_column, second_column, row_num
from
(
select *,
@num := if(@first_column = first_column, 2, 1) as row_num,
@first_column := first_column as c
from mytab order by first_column,id
) as t
having row_num <= 1;
MySQL ワークベンチから、次のようになります。
+----+--------------+---------------+---------+
| id | first_column | second_column | row_num |
+----+--------------+---------------+---------+
| 1 | 1 | 1 | 1 |
| 3 | 2 | 10 | 1 |
| 4 | 3 | 4 | 1 |
+----+--------------+---------------+---------+
そしてPHPから私はこれを得る:
+----+--------------+---------------+---------+
| id | first_column | second_column | row_num |
+----+--------------+---------------+---------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 4 | 1 |
| 3 | 2 | 10 | 1 |
| 4 | 3 | 4 | 1 |
| 5 | 1 | 4 | 1 |
| 6 | 2 | 5 | 1 |
| 7 | 1 | 6 | 1 |
+----+--------------+---------------+---------+
私は何か間違ったことをしていますか?
どうもありがとう!
編集:実際の問題はより複雑なものに結びついているため、これは私の簡素化されたPHPコードです。
class sql_helper extends other
{
public function query_handler($sql, $error_message)
{
$this->connect(); // Not shown, but works without issue
$result = mysql_query($sql) or die($error_message.''.mysql_error());
return $result;
}
public static function sql_result_to_assoc($sql_result)
{
$result_array = array();
while($row = mysql_fetch_assoc($sql_result))
$result_array[] = $row;
return $result_array;
}
public function sql_to_assoc($sql, $error_message)
{
$result = $this->query_handler($sql, $error_message);
return $this->sql_result_to_assoc($result);
}
}
$sql = "
select
id, first_column, second_column, row_num
from
(
select *,
@num := if(@first_column = first_column, 2, 1) as row_num,
@first_column := first_column as c
from mytab order by first_column,id
) as t
having row_num<=1";
$sql_helper = new sql_helper();
$result_array = $sql_helper->sql_to_assoc($sql, '');