我有一个看起来像这样的
的mysql数据库+----+----------+---------+----------------------------------+---------------------+
| id | field_id | user_id | value | last_updated |
+----+----------+---------+----------------------------------+---------------------+
| 1 | 1 | 1 | admin | yyyy-mm-dd hh:mm:ss |
| 3 | 5 | 1 | a:1:{i:0;s:2:"18";} | yyyy-mm-dd hh:mm:ss |
| 4 | 1 | 2 | testuser1 | yyyy-mm-dd hh:mm:ss |
| 5 | 5 | 2 | a:2:{i:0;s:2:"19";i:1;s:2:"18";} | yyyy-mm-dd hh:mm:ss |
+----+----------+---------+----------------------------------+---------------------+
据我所知,正常的sql查询不合适,所以我需要将所有数据拉入php,然后对其进行排序。
我想要的是获取任何具有数字的user_id,在field_id
中说“19”。在该示例中,数组应为“2”。或者我可以在field_id
5中搜索“18”,数组将返回“1,2”。
要获取数据库,我使用以下
<?php
global $wpdb;
$table_name = $wpdb->prefix . "bp_xprofile_data";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name" );
$strDB = maybe_unserialize( $retrieve_data);
echo print_r($strDB, true);
?>
返回:
Array ( [0] => stdClass Object ( [id] => 1 [field_id] => 1 [user_id] => 1 [value] => admin [last_updated] => 2017-09-21 12:38:20 ) [1] => stdClass Object ( [id] => 3 [field_id] => 5 [user_id] => 1 [value] => a:1:{i:0;s:2:"18";} [last_updated] => 2017-09-21 12:38:20 ) [2] => stdClass Object ( [id] => 4 [field_id] => 1 [user_id] => 2 [value] => testuser1 [last_updated] => 2017-09-23 01:43:50 ) [3] => stdClass Object ( [id] => 5 [field_id] => 5 [user_id] => 2 [value] => a:2:{i:0;s:2:"19";i:1;s:2:"18";} [last_updated] => 2017-09-23 01:43:50 ) )
我无法理解如何对这些数据进行排序。我试图找到字符串的部分,但这不起作用。
答案 0 :(得分:1)
您应该可以在&#39;值&#39;上使用LIKE比较。场,例如
SELECT * FROM $table_name AND value LIKE '%9%'
搜索数字的难点在于LIKE也会返回部分匹配,因此查询9也会返回19,91,192等。
但是,根据序列化字符串中双引号包围的值,您应该能够通过在搜索字符串中包含双引号来搜索确切的值,例如: "9"
。
将其添加到您问题的代码中,我们得到:
global $wpdb;
$num_to_find = 19; /* or change to whatever number you need */
$field_id_to_check = 5; /* or change to whatever number you need */
$table_name = $wpdb->prefix . "bp_xprofile_data";
$user_ids = $wpdb->get_results(
$wpdb->prepare(
"SELECT user_id FROM $table_name
WHERE field_id = %d AND value LIKE '%%\"%d\"%%'",
$field_id_to_check, /*this param replaces the 1st %d in the query */
$num_to_find /*this param replaces the 2nd %d in the query */
)
);
print_r($user_ids);
注意:因为查询中包含一个变量而且我不知道它的来源,我使用了$ wpdb-&gt;准备清理变量。
没有经过测试,但我相信它应该可行!
答案 1 :(得分:0)
嗯,第一条规则 - 你不应该这样做。但如果有充分的理由,请考虑将此类查询用于在基于索引的数组中搜索
SELECT * FROM $table_name WHERE value REGEXP '.*;s:[0-9]+:"19".*'
在这里,我们在列值上搜索值 &#34; 19&#34; ,正如您在带有正则表达式的示例中所做的那样。 问候。