I'm trying to search multiple tables in a single database but I'm not having any luck.
I have two tables, Cities and Countries and I want a single search that finds results from both/either
Something like this -
SELECT * FROM cities && countries WHERE name ='New York'
Any help would be awesome!
In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.
This can either be done with a JOIN
or a UNION
clause. Depending on what you want your result to look like. (I'm making some assumptions about your schema in the following examples):
SELECT *
FROM cities
JOIN countries ON (cities.country_id = countries.country_id)
WHERE cities.name = 'New York'
OR countries.name = 'New York'
ALL
if you can, for performance reasons)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'
NATURAL FULL JOIN
NATURAL FULL JOIN
may be used to behave similar to a UNION
if you use it "correctly", as shown in this blog post or in this one.
SELECT *
FROM
(SELECT 'cities' AS source, cities.* FROM cities) cities
NATURAL FULL JOIN
(SELECT 'countries' AS source, countries.* FROM countries) countries
WHERE name = 'New York'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With