我正在尝试在单个数据库中搜索多个表,但我没有运气.
我有两个表,城市和国家,我想要一个搜索,从两个/或两个找到结果
像这样的东西 –
SELECT * FROM cities && countries WHERE name ='New York'
任何帮助都是极好的!
解决方法@H_301_12@
这可以通过JOIN或UNION子句完成.取决于您希望结果的样子. (我在以下示例中对您的架构做了一些假设):
加入
SELECT *
FROM cities
JOIN countries ON (cities.country_id = country.id)
WHERE cities.name = 'New York'
OR countries.name = 'New York'
使用UNION(如果可以,请使用ALL,出于性能原因)
SELECT cities.name,'Is a city' AS type
FROM cities
WHERE cities.name = 'New York'
UNION ALL
SELECT countries.name,'Is a country' AS type
FROM countries
WHERE countries.name = 'New York'
加入
SELECT * FROM cities JOIN countries ON (cities.country_id = country.id) WHERE cities.name = 'New York' OR countries.name = 'New York'
使用UNION(如果可以,请使用ALL,出于性能原因)
SELECT cities.name,'Is a city' AS type FROM cities WHERE cities.name = 'New York' UNION ALL SELECT countries.name,'Is a country' AS type FROM countries WHERE countries.name = 'New York'