gpt4 book ai didi

mysql - 单个mysql查询获取带有ID的数据并获取相关数据

转载 作者:行者123 更新时间:2023-11-29 12:33:14 24 4
gpt4 key购买 nike

我需要形成一个 mysql 查询来从具有 ID 的表中获取*数据,以及与第一个查询的“标题”匹配的 4 个相关数据。

表格名称: feeditems

行:item_iditem_titleitem_description

获取我正在使用的数据

$related_sql = "SELECT * FROM feeditems
WHERE feeditems.item_id='$id' LIMIT 1";

获取我正在使用的相关数据

$related_sql = "SELECT * FROM feeditems
WHERE feeditems.item_id != '$item_row[item_id]'
AND MATCH (feeditems.item_title)
AGAINST ('$item_row[item_title]' IN BOOLEAN MODE)
ORDER BY feeditems.item_id DESC LIMIT 4";

我需要将这两个查询合并为一个查询,因为我使用以下代码给出查询的 json 数据

$set = array();    
$total_records = mysql_num_rows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set['NewsApp'][] = $link;
}
}
echo $val= str_replace('\\/', '/', json_encode($set,JSON_UNESCAPED_UNICODE));

还有什么方法可以使用 json_encode 将上述 2 个查询的结果组合成一个 json 输出。

最佳答案

您可以使用INNER JOIN链接回同一个表:

$related_sql = "SELECT f2.item_id, f2.item_title, f2.item_description 
FROM feeditems f1
INNER JOIN feeditems f2 ON
f1.item_id != f2.item_id AND
MATCH (f2.item_title) AGAINST (f1.item_title IN BOOLEAN MODE)
WHERE f1.item_id='$id'
ORDER BY f2.item_id DESC LIMIT 4";

更新:我发现这不起作用,因为您正在使用MATCH ... AGAINST

“表达式不必是文字字符串,但它必须是在查询评估期间具有常量值的表达式。例如,这允许使用变量,但排除列名称。”

看看http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html#function_match , http://bugs.mysql.com/bug.php?id=66573MySQL Fulltext search against column value?

就像 lolka_polka 所说,使用子查询就可以了:

$related_sql = "SELECT item_id, item_title, item_description 
FROM feeditems
WHERE item_id != '$id' AND
MATCH (item_title) AGAINST ((SELECT item_title FROM feeditems
WHERE item_id='$id' LIMIT 1) IN BOOLEAN MODE)
ORDER BY item_id DESC LIMIT 4";

参见SQLFIDDLE

更新2:使用 UNION

$related_sql = "(SELECT item_id, item_title, item_description 
FROM feeditems
WHERE item_id = '$id' LIMIT 1)
UNION
(SELECT item_id, item_title, item_description
FROM feeditems
WHERE item_id != '$id' AND
MATCH (item_title) AGAINST ((SELECT item_title FROM feeditems
WHERE item_id='$id' LIMIT 1) IN BOOLEAN MODE)
ORDER BY item_id DESC LIMIT 4)
ORDER BY item_id;";

参见SQLFIDDLE

关于mysql - 单个mysql查询获取带有ID的数据并获取相关数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27174870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com