简体   繁体   English

将X和Y插入尚不存在的MySQL数据库

[英]Insert an X and Y into a MySQL database that does not already exist

I have a basic database table for a grid 我有一个网格的基本数据库表

CREATE TABLE `grid` (
  `id` int(10) unsigned NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `customers_id` int(10) unsigned NOT NULL,
  `x` int(11) NOT NULL,
  `y` int(11) NOT NULL,
  `seen` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

I'm trying to get an x and y value from the grid that doesn't already exist in the grid. 我正在尝试从网格中尚不存在的x和y值中获取。 (with means to use it as part of an insert later) I'm using the following but, sometimes, it returns a set of coordinates that do already exist... (使用稍后将其用作插入的一部分的方式)我正在使用以下内容,但有时,它返回一组已经存在的坐标...

PHP 的PHP

private $_maxColumns    = 144;
private $_maxRows       = 90;

MySQL (Within quotes in PHP - hence the curly brackets around the variables) MySQL(在PHP中用引号引起,因此变量周围用大括号括起来)

SELECT
    CONCAT(
        FLOOR( (RAND() * ( {$this->_maxColumns} - 1 + 1 ) ) + 1 ),
        '-',
        FLOOR( (RAND() * ( {$this->_maxRows} - 1 + 1 ) ) + 1 )
    ) as 'random'

    FROM `grid`

    WHERE 'random' NOT IN (
        SELECT CONCAT( `x`, '-', `y` ) FROM `grid`
    )

Any help is much appreciated! 任何帮助深表感谢!

It returns existing values because you got the filter completely wrong: 它返回现有值,因为您使过滤器完全错误:

WHERE 'random' NOT IN (
    SELECT CONCAT( `x`, '-', `y` ) FROM `grid`

In the where criteria you compare the string literal 'random' to subquery that will never ever return this value. 在where条件中,您将字符串文字'random'与永远不会返回该值的子查询进行比较。 In the where clause you cannot filter on a calculated field because the select list is evaluated after the where clause. 在where子句中,无法过滤已计算字段,因为选择列表是在where子句之后求值的。 You can only filter on such fields in the having clause and remove the speechmarks around the word random: 您只能在hading子句中过滤这些字段,并删除random一词周围的语音标记:

SELECT
CONCAT(
    FLOOR( (RAND() * ( {$this->_maxColumns} - 1 + 1 ) ) + 1 ),
    '-',
    FLOOR( (RAND() * ( {$this->_maxRows} - 1 + 1 ) ) + 1 )
) as random

FROM `grid`

HAVING random NOT IN (
    SELECT CONCAT( `x`, '-', `y` ) FROM `grid`
)

However, it is possible that the above query will not return any rows at all. 但是,上述查询有可能根本不返回任何行。 I would rather generate a list of non-existing coordinates within a range and randomly choose one of them. 我宁愿生成一个范围内不存在的坐标的列表,并随机选择其中一个。 I would have a helper table with all possible x - y pairs, just do a left join on the grid table with is null in the where criteria and either use order by rand() limit 1 , or do the random selection from php. 我将拥有一个具有所有可能的x-y对的辅助表,只需在where条件为null的网格表上进行左连接,然后使用order by rand() limit 1 ,或者从php中进行随机选择。

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

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