简体   繁体   English

如何在 php 上的 SQL 上进行反向 LIKE?

[英]How can I do an inverse LIKE on SQL on php?

I want to select a value from a database in sql with php.我想 select sql 和 php 中的数据库中的一个值。 So, the value that I want to select is a part of the value which I compare it with.因此,我想要 select 的值是我与之比较的值的一部分。

There are two tables: one is called event and the other weekly.有两张表:一张称为事件,另一张称为每周。 In the table event, there is a column called name, that is the name of each event.在表事件中,有一列叫做名称,即每个事件的名称。 Weekly has also a column called name, and it´s the name of the weekly. Weekly 还有一个名为 name 的列,它是每周的名称。 So, I want to get the id from a weekly comparing the two names.所以,我想从每周比较两个名称中获取 id。 But the name of the event can have something before and/or after the name.但是事件的名称可以在名称之前和/或之后有一些东西。 For example:例如:

Weekly name: Monday

Weekly id: 1

Event: NJK Monday 3


Another example:

Weekly name: Tuesday

Weekly id: 2

Event: Tuesday ks

I´ve tried to do it with a LIKE condition, but I didn´t earn the result that I wanted.我试过用 LIKE 条件来做,但我没有得到我想要的结果。

$stmt = $conn->prepare("UPDATE db.event SET weeklyid ="
                    . " (SELECT id FROM db.weekly WHERE %name%"
                    . " LIKE  'NJK Monday 3') WHERE name = :name;");
            $stmt->bindValue('name', $event->name);
            $stmt->execute();

So, it´s like an inverse LIKE.所以,它就像一个反向的 LIKE。 The result that I want to get from the code above would be that the select sentence return 1.我想从上面的代码中得到的结果是 select 语句返回 1。

You can use CONCAT() to add the % symbols around the attribute like this您可以使用CONCAT()在属性周围添加%符号,如下所示

SELECT id FROM db.weekly WHERE 'NJK Monday 3' LIKE CONCAT('%', name, '%')

I'm not sure how it works with named placeholders by if you will use ?我不确定它如何与命名占位符一起使用,您是否会使用? placeholder you should add % to execute values not to query:占位符,您应该添加%来执行不查询的值:

wrong错误的

$stmt = $conn->prepare('SELECT id FROM db.weekly WHERE name LIKE %?%');
$stmt->execute(['NJK Monday 3']);

good好的

$stmt = $conn->prepare('SELECT id FROM db.weekly WHERE name LIKE ?');
$stmt->execute(['%NJK Monday 3%']);

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

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