MYSQL索引作为查询中的变量

时间:2016-07-27 14:38:13

标签: php mysql indexing

我试图从2列中获取条件并使用此查询对其进行索引

$query1 = "SET @row_num = 0";
$query2 = "SELECT *, @row_num := @row_num + 1 as row_index FROM gift 
           WHERE Category = '0' AND ID ='".$ID."'
           ORDER BY ID ASC;";
mysqli_query($conn, $query1);

$retrieve = mysqli_query($conn, $query2);

是否有一种方法可以将row_index用作查询中的变量,如下所示:

$query1 = "SET @row_num = 0";
$query2 = "SELECT *, @row_num := @row_num + 1 as row_index FROM gift
           WHERE Category = '0' AND row_index ='".$ID."'
           ORDER BY ID ASC;";
mysqli_query($conn, $query1);

$retrieve = mysqli_query($conn, $query2);

2 个答案:

答案 0 :(得分:3)

您可以在$ID子句中测试HAVING

$query1 = "SET @row_num = 0";
$query2 = "SELECT *, @row_num := @row_num + 1 as row_index FROM gift
           WHERE Category = '0' 
           HAVING row_index = $ID
           ORDER BY ID ASC;";
mysqli_query($conn, $query1);

$retrieve = mysqli_query($conn, $query2);

无需在查询中连接变量。如果$ID是整数,则不需要引号,如果它是字母数字,只需将其括在单引号中,因为PHP将正确插入变量。

Reference for HAVING clause

答案 1 :(得分:0)

如果没有对它进行测试,我希望以下内容能够正常工作......

SELECT ilv.*
FROM (
   SELECT gift.*, @row_num := @row_num + 1 as row_index 
   FROM gift
   WHERE Category = '0' 
   ORDER BY ID ASC
) ilv
WHERE row_index ='".$ID."';

(但你不应该引用一个整数值)。

或者....

SELECT *
FROM gift
WHERE Category = '0' 
ORDER BY ID ASC
LIMIT $ID, 1;

或者,对于最近使用MyISAM引擎的MySQL,您可以define a primary key based on a natural key and autoincrement value。在你的情况下,"自然"关键是类别。然后,如果您确保以单调间隔在数据库中分配id 存储并且只是.....

SELECT *
FROM gift
WHERE category='0'
AND id=($ID * $interval);