For each row from one table only one row from another table (mysql)
I use MySQL 5.1. I have two tables T1(hash, value) and T2(hash, value) and I connect them using hash
. They contain:
----
T1
----
1 A
2 B
3 C
4 D
----
T2
----
1 E
1 F
3 G
4 H
My purpose is to get all rows from T1 which has connection with any row from T2.
I tried to do so with:
SELECT T1.* FROM T1 LEFT JOIN T2 ON T1.h开发者_JAVA百科ash = T2.hash;
But I failed with two 'A' from T1 in the an output. Where am I wrong?
SELECT T1.hash, T1.value
FROM T1
WHERE EXISTS(
SELECT *
FROM T2
WHERE T1.hash = T2.hash);
If you wanted to use a JOIN it would need to be
SELECT DISTINCT T1.hash, T1.value
FROM T1
INNER JOIN T2 ON T1.hash = T2.hash;
In SQL Server the first one is more efficient. I don't know for MySQL though.
SELECT T1.*
FROM T1
WHERE EXISTS ( SELECT T2.hash
FROM T2
WHERE T2.hash = T1.hash
)
精彩评论