2013-03-14 94 views
0

我有2個表所示:MySQL搭配同一個表中選擇的行不where子句

表1

 
+----+-----------+--------------------+ 
| ID | Postcode4 |  woonplaats  | 
+----+-----------+--------------------+ 
| 1 |  9044 | Beetgum   | 
| 2 |  9045 | Beetgummermole  | 
| 3 |  1028 | Amsterdam   | 
| 4 |  1029 | Amsterdam   | 
| 5 |  1030 | Amsterdam   | 
+----+-----------+--------------------+ 

表2

 
+----+------+-------+ 
| ID | 4PP | Regio | 
+----+------+-------+ 
| 1 | 9044 |  2 | 
| 2 | 9045 |  2 | 
| 3 | 1028 |  4 | 
| 4 | 1029 |  4 | 
| 5 | 1030 |  4 | 
+----+------+-------+ 

我首先要在選擇區域選擇性在這種情況下,Beetgum是regio 2.然後我想要表2中的所有其他4PP都有相同的區域(2)。因此,查詢的結果必須是9044,9045

回答

3

,這裏是一個加入一個:)

SELECT t2.* 
FROM Table1 
INNER JOIN Table2 ON Table2.4PP = Table1.Postcode4 
INNER JOIN Table2 t2 ON t2.Regio = Table2.regio 
WHERE Table1.woonplaats = 'Beetgum' 

小提琴:http://sqlfiddle.com/#!2/347f3/3

+0

沒錯!但並不快...幾乎1秒的查詢。索引的最佳位置在哪裏? Woonplaats或4PP? – 2013-03-14 20:15:40

+1

sqlfiddle。這是我最喜歡的一天。我沒有聽說過這個。 – 2013-03-14 20:15:50

+2

@MikeC。最好的事情是,你可以貼上漂亮的ascii藝術表並獲得DDL! – hank 2013-03-14 20:17:07

0

這應該這樣做

select 4PP from table2 where Regio in (select Regio from table2 where 4PP in (select PostCode4 from table1 where woonplaats = "Beetgum")) 
1

這裏是一個非常糟糕的查詢,直到有人給你看上一個連接(你應該再使用)

select t.4PP from Table2 t 
WHERE t.Regio in 
(
    select Regio 
    from Table2 t2 
    join Table1 t1 on t2.4PP=t1.Postcode4 
    where t1.woonplats='Beetgum' 
) 
0

看來,這是你在找什麼:

SELECT GROUP_CONCAT(Table3.4PP) 4PP FROM Table1 
INNER JOIN Table2 ON(Table1.PostCode4 = Table2.4PP) 
INNER JOIN Table2 AS Table3 ON(Table2.Regio = Table3.Regio) 
WHERE woonplaats = 'Beetgum'; 

Demo