DBのレコードに

ID colA
------------
1 a
2 b
3 c
とあった場合
表示上は、
ID before after
-------------------
1 - a
2 a b
3 b c
のように表示させたいです。

DBからレコードを取得したものをvar_dumpすると
以下のような形になるのですが、

object(Zend\Db\ResultSet\ResultSet)[509]
protected 'allowedReturnTypes' =>
array
0 => string 'arrayobject' (length=11)
1 => string 'array' (length=5)
protected 'arrayObjectPrototype' =>
object(Application\Db\Row\hist)[493]
protected 'returnType' => string 'arrayobject' (length=11)
protected 'buffer' => int -1
protected 'count' => int 19
protected 'dataSource' =>
object(ArrayIterator)[512]

array
'col1' => string '1' (length=1)
'col2' => string 'a' (length=1)

array
'col1' => string '2' (length=1)
'col2' => string 'b' (length=1)

array
'col1' => string '3' (length=1)
'col2' => string 'c' (length=1)

どのようにコードを組んだらよいか、
サンプルを教えていただきたいです。
phpのバージョンは5.3です

回答の条件
  • 1人1回まで
  • 登録:
  • 終了:2014/10/08 13:52:48
※ 有料アンケート・ポイント付き質問機能は2023年2月28日に終了しました。

ベストアンサー

id:pogpi No.1

回答回数428ベストアンサー獲得回数59

ポイント200pt

表示だけなら、SELECTした結果を処理するwhileループ内で、変数に前回のcolAを持たせればいいだけです。

$before = "-";
while(・・・) {
処理
$before = (colAの値);
}

id:yayayai

ありがとうございます!

2014/10/08 13:51:47

その他の回答1件)

id:pogpi No.1

回答回数428ベストアンサー獲得回数59ここでベストアンサー

ポイント200pt

表示だけなら、SELECTした結果を処理するwhileループ内で、変数に前回のcolAを持たせればいいだけです。

$before = "-";
while(・・・) {
処理
$before = (colAの値);
}

id:yayayai

ありがとうございます!

2014/10/08 13:51:47
id:gizmo5 No.2

回答回数504ベストアンサー獲得回数141

SQL だけでやるとしたら、他にもやり方はありますがこのようなSQLになります。

select T4.ID,
	case when T4.before IS NULL then '-' else T4.before end as 'before',
	T4.after
	from (
		select T3.ID, T3.colA as after,
			(select T1.colA
				from tbl T1
				where T1.ID = (
					select max(T2.ID)
						from tbl T2
						where T3.ID > T2.ID)
						) as 'before'
			from tbl T3
			order by T3.ID) T4

コメントはまだありません

この質問への反応(ブックマークコメント)

「あの人に答えてほしい」「この質問はあの人が答えられそう」というときに、回答リクエストを送ってみてましょう。

これ以上回答リクエストを送信することはできません。制限について

回答リクエストを送信したユーザーはいません