我正在尝试搜索我的完整网站,但我不确定如何进行查询。
$query = "SELECT * FROM
game_content,
tech_content,
hint_content
WHERE
title LIKE '%".$input."%'
description LIKE '%".$input."%'";
我要搜索的表格是:game_content,tech_content,hint_content&列是:标题,描述每个表都有这些列
说实话,我很困惑使用JOIN我得到了很多意想不到的结果。
答案 0 :(得分:0)
我建议单独搜索每个表格,或者您可以在选择部分中使用tech_content.name as name , hint_content.name as name
等等,请参阅我选择了名称相似的行
和union
用于选择每个表
答案 1 :(得分:0)
你可以这样做:
SELECT 'game_content' as source, * FROM game_content WHERE <your condition>
UNION
SELECT 'tech_content' as source, * FROM tech_content WHERE <your condition>
UNION
<further tables>;
将所有表的结果连接到一个结果集中。
答案 2 :(得分:0)
您需要使用联接
SELECT game_content.*, tech_content.*, hint_content.*
FROM game_content
JOIN tech_content
ON tech_content.aID = game_content.bID
JOIN hint_content
ON hint_content.cID = tech_content.bID
WHERE game_content.title LIKE '%".$input."%'
and game_content.description LIKE '%".$input."%'"';
确保已创建关系(约束)!
注意:强>
- 这种方式你的查询会像永远一样,这是通过sql执行此操作的最快方法!但表现明智很差!
因为你要加入所有数据,然后开始整理出来!如果您的表很大,那么您就会遇到问题 - 查询将永远存在!
答案 3 :(得分:0)
如果条件中的条件字段名称和返回的字段名称相同,则没有别名会更短。它应该类似于follow(tableName字段告诉你结果来自哪个表)
"SELECT gameField1 AS fld1, gameField2 AS fld2, 'game' AS tableName FROM game_content WHERE gameTitle LIKE '%".$input."%' AND gameDescription LIKE '%".$input."%'
UNION
SELECT techField1 AS fld1, techField2 AS fld2, 'tech' AS tableName FROM tech_content WHERE techTitle LIKE '%".$input."%' AND gameDescription LIKE '%".$input."%'
UNION
SELECT hintField1 AS fld1, hintField2 AS fld2, 'hint' AS tableName FROM hint_content WHERE hintTitle LIKE '%".$input."%' AND hintDescription LIKE '%".$input."%'"
答案 4 :(得分:0)
如果每个表都有一个id主键列(或类似),则可以创建一个视图;
CREATE VIEW all_content AS
SELECT CONCAT('g',id) AS id, title, description FROM game_content
UNION
SELECT CONCAT('t', id) AS id, title, description FROM tech_content
UNION
SELECT CONCAT('h', id) AS id, title, description FROM hint_content
然后查询视图
答案 5 :(得分:0)
在尝试了一些你的答案后,我决定做Dieter在评论中提出的建议。
//set the queries.
$query[1] = "SELECT * FROM game_content WHERE title LIKE '%".$input."%' OR description LIKE '%".$input."%'";
$query[2] = "SELECT * FROM hint_content WHERE title LIKE '%".$input."%' OR description LIKE '%".$input."%'";
$query[3] = "SELECT * FROM tech_content WHERE title LIKE '%".$input."%' OR description LIKE '%".$input."%'";
//loop the queries setting the results
for ( $i = 1; $i <= 3; $i++ ) {
$result[$i] = mysqli_query( $connection, $query[$i] );
check_query( $result[$i] );
while( $row = mysqli_fetch_assoc( $result[$i] ) ) {
//display output
}
}
这只是一个小网站,所以这就足够了。