php - 在不同的mysql表中搜索不同的列
问题描述
我一个一个地执行这两个查询,但是我需要将这两个查询作为一个查询同时执行,并从mysql数据库中获取一次结果
我尝试了 UNION SELECT 但由于从不同的表中选择不同的列(模型,模型编号)它不起作用
有人知道sql查询结构来帮助我解决这个问题吗?
查询 1
$query = "SELECT post_id,SUBSTR(post_name, 1 ,30) as post_name,price,username,poster_folder_id FROM realestate
USE INDEX(idx_post_id,idx_name,idx_price,idx_username,idx_poster_folder_id)
WHERE post_name LIKE ? OR description LIKE ? OR price LIKE ? ORDER BY post_id DESC LIMIT 10";
查询 2
$query = "SELECT post_id,SUBSTR(post_name, 1 ,30) as post_name,price,username,poster_folder_id FROM cars
USE INDEX(idx_post_id,idx_name,idx_price,idx_username,idx_poster_folder_id)
WHERE post_name LIKE ? OR description LIKE ? OR model LIKE ? OR modelsnumber LIKE ? OR price LIKE ? ORDER BY post_id DESC LIMIT 10";
我试过了
$query = "SELECT post_id,SUBSTR(post_name, 1 ,30) as post_name,price,username,poster_folder_id FROM realestate
WHERE post_name LIKE ? OR description LIKE ? OR price LIKE ? ORDER BY post_id DESC LIMIT 10
UNION
SELECT post_id,SUBSTR(post_name, 1 ,30) as post_name,price,username,poster_folder_id FROM cars
WHERE post_name LIKE ? OR description LIKE ? OR model LIKE ? OR modelsnumber LIKE ? OR price LIKE ? ORDER BY post_id DESC LIMIT 10";
解决方案
UNION 中带有 ORDER BY 和/或 LIMIT 的单独子查询必须用括号括起来:
$query = "
(SELECT post_id,SUBSTR(post_name, 1 ,30) as post_name,price,username,poster_folder_id
FROM realestate
WHERE post_name LIKE ? OR description LIKE ? OR price LIKE ? ORDER BY post_id DESC LIMIT 10
)
UNION
(SELECT post_id,SUBSTR(post_name, 1 ,30) as post_name,price,username,poster_folder_id
FROM cars
WHERE post_name LIKE ? OR description LIKE ? OR model LIKE ? OR modelsnumber LIKE ? OR price LIKE ? ORDER BY post_id DESC LIMIT 10
)";
推荐阅读
- python - 如何在 django 中设置 google OAuth 的详细指南?
- php - HTML 如果第一个选项被禁用,则选择不发布
- c - UDP套接字创建和通信是否应该只在主函数中完成?
- javascript - Console.log() 和 el.innerText 立即重置(帮助)
- django - Django - 在使用 unique=True 保存时处理 URLField 的额外斜线
- reactjs - 反应js中的范围派克
- jruby - 适用于 OpenJDK 8 (Zulu JDK) 的 Jruby 版本
- php - 没有“where”的查询仍然处理“where”
- logging - Serilog - 最新文件不应该有时间戳
- angular - 与 Angular 项目相比,Angular Nativescript 项目中的模块组件结构和延迟加载是否相同?