Php 使用regexp从数据库查询

Php 使用regexp从数据库查询,php,sql,Php,Sql,在数据库表1中,我有realpath-details.html?cat_id=48&id=295, 在表2中,id为295。我是否可以从表1中选择单元格,其中url中的id=id表2中的id?我这样做了,但不起作用: $sql = one.realpath, two.id FROM one, two WHERE one.realpath REGEXP '[0-9]+$' = two.id 编辑- 正如你们提到的,这个数字不应该是静态的- 你可以试试这个- $myNumber = 295; /

在数据库表1中,我有realpath-details.html?cat_id=48&id=295, 在表2中,id为295。我是否可以从表1中选择单元格,其中url中的id=id表2中的id?我这样做了,但不起作用:

$sql = one.realpath, two.id FROM one, two WHERE one.realpath REGEXP '[0-9]+$' = two.id 
编辑- 正如你们提到的,这个数字不应该是静态的-

你可以试试这个-

$myNumber = 295; // If you want to define it in a variable and then use if
$myNumber = myCheckingFunction(); // If the value is returned from a function
或者试试这个-

$myNumber = 295; // If you want to define it in a variable and then use if
$myNumber = myCheckingFunction(); // If the value is returned from a function
或者试试这个-

$myNumber = $someRowFromDB['field_name']; // If you are trying to fetch it from a db row
然后你可以用这样的代码替换它-

$searchNeedle = 'id=' . $myNumber;
$query = "select * from tablename where two.realpath like '%$searchNeedle'";

如果您的表1如下所示:

select * from one;

+-------------------------------+
| realpath                      |
+-------------------------------+
| details.html?cat_id=48&id=295 |
| details.html?cat_id=48&id=234 |
+-------------------------------+
SELECT one.realpath, two.id FROM one
INNER JOIN two ON (one.realpath REGEXP CONCAT(two.id, '$'))

+-------------------------------+----+
| realpath                      | id |
+-------------------------------+----+
| details.html?cat_id=48&id=295 |  5 |
+-------------------------------+----+
如果您在sql控制台中执行您的表达式:

SELECT one.realpath REGEXP '[0-9]+$' TEST FROM one
此查询返回

+------+
| TEST |
+------+
|    1 |
|    1 |
+------+
因此,当你尝试

WHERE one.realpath REGEXP '[0-9]+$' = two.id
你正在做:

WHERE '1' = two.id
您可以尝试此查询。这可能更好,但它正在发挥作用:

SELECT one.realpath, two.id FROM one
INNER JOIN two ON (one.realpath REGEXP CONCAT('id=',two.id, '$'))
结果是:

+-------------------------------+-----+
| realpath                      | id  |
+-------------------------------+-----+
| details.html?cat_id=48&id=295 | 295 |
+-------------------------------+-----+
添加'id='很重要,因为如果不添加此项,可能会得到如下结果:

select * from one;

+-------------------------------+
| realpath                      |
+-------------------------------+
| details.html?cat_id=48&id=295 |
| details.html?cat_id=48&id=234 |
+-------------------------------+
SELECT one.realpath, two.id FROM one
INNER JOIN two ON (one.realpath REGEXP CONCAT(two.id, '$'))

+-------------------------------+----+
| realpath                      | id |
+-------------------------------+----+
| details.html?cat_id=48&id=295 |  5 |
+-------------------------------+----+

好的,但数字不是静态的。我必须检查编号,然后从表中选择