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 schemaname.tablename.fieldname.
Of course, all tables referenced in the WHERE and SELECT clauses should be included in the FROM clause.
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.
Examples:
...
FROM table1 AS t1
WHERE t1.field1 = somevalue
OR EXISTS (
SELECT *
FROM table2 AS t2
WHERE t2.somefield = someothervalue
)
...
or
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;
Related
I need to join two tables in SQL. There are no common fields. But the one table have a field with the value krin1001 and I need it to be joined with the row in the other table where the value is 1001.
The idea behind the joining is i have multiple customers, but in the one table there customer id is 'krin1001' 'krin1002' and so on, in this table is how much they have sold. In the other table there customer is is '1001' '1002' and so on, and in this table is there name and adress and so on. So it will always be the first 4 charakters i need to strip from the field before matching and joining. It might not always be 'krin' i need it to work with 'khjo1001' also, and it still needs to join on the '1001' value from the other table.
Is that possible?
Hope you can help me.
You need to use substring:
ON SUBSTRING(TableA.Field, 5, 4) = TableB.Field
Or Right:
ON RIGHT(TableA.Field, 4) = TableB.Field
You can also try to use CHARINDEX function for join operation. If value from table1 contains value from table2 row will be included in result set.
;WITH table1 AS(
SELECT 'krin1001' AS val
UNION ALL
SELECT 'xxx'
UNION ALL
SELECT 'xyz123'
),
table2 AS(
SELECT '1001' AS val
UNION ALL
SELECT '12345'
UNION ALL
SELECT '123'
)
SELECT * FROM table1 AS t
JOIN table2 AS T2 ON CHARINDEX(T2.val, T.val) > 0
Use it as:
SELECT
*
FROM table t1
INNER JOIN table t2 ON RIGHT(t1.col1, 4) = t2.col1;
I have two interconnected tables: one stores some general result (table1), the other one details N rows for each result (table2).
Each record in table2 has a field recording the "auto_id" of the table1 row of reference (field is called "ref_id")
I intentionally deleted some records from the table1, but I left the referenced rows in table2.
How can I find all rows with invalid "ref_id"s in table2 that link to a no more existing "auto_id" in table1?
I was thinking something like
SELECT *
FROM table2
WHERE NOT EXISTS(
SELECT auto_id
FROM 'table1'
WHERE 'table2.res_id' = auto_id
)
but there-s obviously some error.
Thanks for the help!
You are using the wrong quotes. Single-quotes (apostrophes, or ASCII 39) are for literal strings. The easiest solution would be to remove the quotes:
SELECT *
FROM table2
WHERE NOT EXISTS(
SELECT auto_id
FROM table1
WHERE table2.res_id = auto_id
);
If you want to quote identifiers in MySQL, use backticks (ASCII 96).
SELECT *
FROM `table2`
WHERE NOT EXISTS(
SELECT auto_id
FROM `table1`
WHERE `table2`.`res_id` = `auto_id`
);
The cleanest way IMHO is an outer join filtering for missing rows:
SELECT t2.*
FROM table2
LEFT JOIN table1 t1 ON t1.auto_id = t2.res_id
WHERE t1.auto_id IS NULL
This works because missed left joins have all nulls in their columns and where clause conditions are applied after the join is made - the IS NULL condition means the only rows returned are those that don't have a matching row in the other table.
As well as being the most efficient (assuming an index on table1.auto_id), it also makes for a briefer query than a NOT IN (...) query.
MySQL JOIN is the best option for you.
Try this:
SELECT *
FROM table2 T2
JOIN table1 T1
ON T2.`res_id` != T1.`auto_id`
I have 2 tables in MySQL, the first one has 2 columns: ID and name, the second has 3 columns: firstTableId (foreign key on the first table), key, value.
I have the following rows in table 1:
1,Bob
2,Alice
3,Fred
I have the following rows in table 2:
1,age,20
1,gender,male
2,age,20
2,gender,female
3,age,18
3,gender,male
I would like to write a select query using only the last 2 columns on the second table (key and value) that returns only Bob form the first table, but I can't seem to figure it out.
Essentially I want to select from the first table all rows where, in the second table, we have key=age and value=20 for one row, and key=gender and value=male in another row. Can anyone point me in the right direction ? Manipulating table structure is not preferred as this is a simplified example and both "key" and "value" columns in the second table can be pretty much anything, it's not actually limited to "age" and "gender".
Thanks in advance.
You can do this with a self join like this:
select
*
from
table1 t1
inner join table2 age on t1.id = age.id
inner join table2 gender on t1.id = gender.id
where
(age.`key` = 'age' and age.value = 20)
and
(gender.`key` = 'gender' and gender.value = 'male')
An additional tactic you may want to try is a PIVOT query. Mysql doesnt have anything native to support pivot's, but there are several examples of how to do them.
You can see it working in this fiddle
Use two IN clauses (or two EXISTS clauses).
select *
from table1
where id in (select firstTableId from table2 where key = 'age' and value = '20')
and id in (select firstTableId from table2 where key = 'gender' and value = 'male');
With EXISTS:
select *
from table1
where exists (select * from table2 where key = 'age' and value = '20' and firstTableId = table1.firstTableId)
and exists (select * from table2 where key = 'gender' and value = 'male' and firstTableId = table1.firstTableId);
"I have 3 Tables which is Admin table,Studentinfo Table and Useraccount Table.
i want to join that 3 tables for my search engine. :(
im beginner in sql anyone can help me?"
SELECT Username,Name,Position,Status,ImageName FROM useraccount
JOIN admin ON admin.username = useraccount.username
JOIN studentinfo ON studentinfo.username = useraccount.username
where Name Like '%Search%';
"That is my code but nothing happen."
When dealing with multiple tables you would have to compensate for column name ambiguity as the same column name could be available in other joining tables and there is no way for the query execution engine to know which one you want returned.
You can easily fix this by adding an alias or table name to referenced column Name
TableAlias.ColumnName
( or )
TableName.ColumnName
Example:
SELECT Col1
FROM table1
JOIN table2
ON table1.Col1= table2.Col2
Will generate a Ambiguous column name error.
SELECT t1.Col1
FROM table1 t1
JOIN table2 t2
ON t1.Col1= t2.Col2
Or
SELECT table1.Col1
FROM table1
JOIN table2
ON table1.Col1= table2.Col2
The changes:
Added the prefix "t1" or "TableName" to the requested column, so that the engine knows which table we want the data from
Added table aliases in the FROM / JOIN clauses to shorten the code
Scenario Example:
SELECT <TableName>.Username,
<TableName>.Name,
<TableName>.Position,
<TableName>.Status,
<TableName>.ImageName
FROM useraccount
JOIN admin
ON admin.username = useraccount.username
JOIN studentinfo
ON studentinfo.username = useraccount.username
WHERE <TableName>.Name LIKE '%Search%';
I have two tables,
table1 and table2 both tables has these columns
id, name, rel_id
now i would like to have a query to count ids of the table1 where name from table2 is equals to john and table1 rel_id equals to table2 rel_id.
so something like this (this is not correct that's why i need help to make it work).
Select count(ids) from table1
where table2.name="john"
and table1.rel_id=table2.rel_id
Well, one way is to use a join:
Select count(t1.id)
from table1 t1 join
table2 t2
on t1.rel_id = t2.rel_id
where t2.name = 'john';
Note that this uses table aliases to distinguish all the columns in each table. Because the tables have the same columns, you need to identify the table for each column. Also, the I changed the string constant to use single quotes rather than double quotes.
You need to look into joins so :
select count(ids)
from table1 join table2 on table1.rel_id=table2.rel_i
where table2.name="john"
A short intro from W3C schools: http://www.w3schools.com/sql/sql_join.asp
The full MySQL URL for more reference http://dev.mysql.com/doc/refman/5.0/en/join.html