I know that I can use the OR SQL operator on the same column of a table like the following:
SELECT * FROM users WHERE last_name = 'Peter' OR last_name = 'Smith';
But the situation I have right now is that I'm trying to use the OR operator on two different tables (different column names). Is that possible? How can I achieve that in an SQL query?
And yes there is a foreign key column that links one table to the primary key column of the other table.
Thanks in advance for any help.
If the fields in the different tables have the same name, you can distinguish them with
tablename.fieldname, if the tables have the same name (in different schemas), you can further qualify the names with
Of course, all tables referenced in the
SELECT clauses should be included in the
Note: If a table is aliased in the
FROM, the alias should be used instead of the table name.
You cannot display (or use in WHERE conditions, etc...) fields from a table that not included in the
FROM; however, you can use subqueries on those tables.
... FROM table1 AS t1 WHERE t1.field1 = somevalue OR EXISTS ( SELECT * FROM table2 AS t2 WHERE t2.somefield = someothervalue ) ...
SELECT t1.field1 , (SELECT t2.somefield FROM table2 AS t2 WHERE t2.anotherfield = somevalue LIMIT 1) AS t2Val FROM table1 AS t1
Yes , it is possible
SELECT users.* FROM users,countries WHERE users.last_name = 'Peter' OR countries.name = 'mexico' AND users.idCountry=countries.id;