使用regexp从DB查询

时间:2014-09-11 10:46:14

标签: php sql

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

$sql = one.realpath, two.id FROM one, two WHERE one.realpath REGEXP '[0-9]+$' = two.id 

2 个答案:

答案 0 :(得分:0)

编辑 - 如你所说,数字不应该是静态的 -

你可以试试这个 -

$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 :(得分:0)

如果您的表格如下:

select * from one;

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

如果你在sql console中执行expresion:

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 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 |
+-------------------------------+----+