如何将两个不相关的表合并为一个SQL select语句请求。但是,两个表都必须具有“匹配”和“针对”功能才能进行全文搜索。我得到一个空白响应,当我执行单个表SQL匹配并针对请求进行匹配时,它工作正常,但当我执行两个表时却无法正常工作。
表一:传输-只有id是主键整数auto_increment,其余是varchar
+----+---------+-----------+--------------+
| id | title | type | tags |
+----+---------+-----------+--------------+
| 1 | triumph | motorbike | sport, black |
+----+---------+-----------+--------------+
| 2 | bmw | car | hatchback |
+----+---------+-----------+--------------+
表二:汽车--只有id是主键整数auto_increment,其余是varchar
+----+-----------+-----------+------------+---------+
| id | name | kind | link | listed |
+----+-----------+-----------+------------+---------+
| 1 | suzuki | motorbike | /bike/new/ | green |
+----+-----------+-----------+------------+---------+
| 2 | volkwagan | car | /car/new/ | limited |
+----+-----------+-----------+------------+---------+
我需要它来打印出这样的内容(只是注意,不确定我将如何使用id-可能有两列id_automobile和id_transport引用了以上两个表)
+----+-----------+-----------+------------+--------------+
| id | title | type | link | tags |
+----+-----------+-----------+------------+--------------+
| 1 | suzuki | motorbike | /bike/new/ | green |
+----+-----------+-----------+------------+--------------+
| 2 | triumph | motorbike | | sport, black |
+----+-----------+-----------+------------+--------------+
| 3 | bmw | car | | hatchback |
+----+-----------+-----------+------------+--------------+
| 4 | volkwagan | car | /car/new/ | limited |
+----+-----------+-----------+------------+--------------+
我的尝试失败:
<table>
<tr>
<th>Title</th>
<th>Type</th>
<th>Link</th>
<th>Tags</th>
</tr>
if(isset($_GET['search'])) {
$search = $_GET['search'];
} else {
$search = '';
}
$sql = "SELECT * FROM `transport` WHERE MATCH(title, tags) AGAINST('".$search."') CROSS JOIN `automobile` WHERE MATCH(name, listed) AGAINST('".$search."')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["title"]."</td><td>".$row["type"]."</td><td>".$row["link"]."</td><td>".$row["tags"]."</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
</table>
请您提供帮助
答案 0 :(得分:0)
UNION
子句应为您提供所需的结果。
只要确保SELECT
与UNION
组合在一起,就具有相似的列集。您可以使用AS
来定义别名。
类似这样的东西:
SELECT title, type, '' AS link, tags
WHERE MATCH(title, tags) AGAINST('...')
FROM transport
UNION
SELECT name AS title, kind AS type, link, listed AS tags
FROM automobile
WHERE MATCH(title, kind) AGAINST('...')