我已经看到SQL Server中有一个名为 ROW_NUMBER 的函数,在我的情况下,我要联接3个表,每个表的ID列都有不同的名称(为 jsTree plugin )
我有此代码:
$sql= "(SELECT
c1.idcarrera AS id,
c1.nombre as text,
null as parent_id
FROM siiupv.carrera AS c1)";
$sql.=" UNION ALL ";
$sql.= " (SELECT
pe.idplan_estudios AS id,
pe.clave AS text,
pe.idcarrera as parent_id
FROM siiupv.plan_estudios AS pe)";
$sql.=" UNION ALL ";
$sql.= " (SELECT idcarga AS id, c2.clave AS text, idplan_estudios as parent_id FROM siiupv.carga AS c2)";
$qResults = $pdo->prepare($sql);
$qResults->execute();
$count = $qResults->rowCount();
while($m = $qResults->fetch(PDO::FETCH_ASSOC)){
echo '<tr><td> '.$m["id"].'</td><td>'.$m["text"].'</td><td>'.$m["parent_id"].'</td></tr>';
}
它产生以下输出:
+------+------------------+
| id | text | parent_id |
+------+------------------+
| 1 | A1 | NULL |
| 2 | A2 | NULL |
| 3 | A3 | NULL |
| 1 | B1 | 1 |
| 2 | B2 | 2 |
| 3 | B3 | 1 |
| 4 | B4 | 2 |
| 5 | B5 | 5 |
| 1 | C1 | 4 | Note! (Child of "B4")
| 2 | C2 | 4 | Note! (Child of "B4")
+------+------------------+
但是我想得到:
+------+------------------+
| id | text | parent_id |
+------+------------------+
| 1 | A1 | NULL |
| 2 | A2 | NULL |
| 3 | A3 | NULL |
| 4 | B1 | 1 |
| 5 | B2 | 2 |
| 6 | B3 | 1 |
| 7 | B4 | 2 |
| 8 | B5 | 5 |
| 9 | C1 | 7 | Note! (Child of "B4")
| 10 | C2 | 7 | Note! (Child of "B4")
+------+------------------+
注意!>这些ID已遍历,因此必须具有值7
我想至少获得自动增量ID的帮助
答案 0 :(得分:1)
向结果集的每个记录添加行号的一种方法是使用会话变量:
"Great Britain"
答案 1 :(得分:0)
不确定我是否真的遇到问题,但是您可以通过添加前缀或其他内容来生成新的唯一ID。
选择CONCAT(“ A-”,idcarga)AS ID,c2.clave AS文本,CONCAT(“ A-”,idplan_estudios)作为parent_id