简体   繁体   English

MYSQL索引作为查询中的变量

[英]MYSQL Index as a variable in a query

I'm trying to get a criteria from 2 Columns and indexing them using this query 我试图从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);

Is there is a way in which I can use the row_index as a variable in the query, like this: 有没有一种方法可以将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);

You can test for the $ID in a HAVING clause: 您可以在HAVING子句中测试$ID

$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);

There is no need to concatenate the variable in the query. 无需在查询中连接变量。 If $ID is an integer there is no need for quotes and if it is alpha-numeric just enclose it in single-quotes as PHP will interpolate the variable correctly. 如果$ID是整数,则不需要引号;如果它是字母数字,则只需将其括在单引号中,因为PHP会正确插入变量。


Reference for HAVING clause HAVING子句的参考

Without actually having tested it, I would expect something like the following to work.... 在没有实际测试的情况下,我希望可以进行以下操作。

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."';

(but you shouldn't be quoting an integer value). (但您不应该引用整数值)。

Or.... 要么....

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

Or, with a recent MySQL, using the MyISAM engine, you can define a primary key based on a natural key and autoincrement value . 或者,在最近的MySQL中,使用MyISAM引擎,您可以基于自然键和自动增量值定义主键 In your case, the "natural" key would be category. 在您的情况下,“自然”键将是类别。 Then if you ensure that you are allocating the id stored in the database at a monotonic interval and simply..... 然后,如果您确定要以单调的间隔分配存储在数据库中的id,并且简单.....

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM