简体   繁体   中英

Mysql select rows with same table not in where clause

I have 2 tables like this:

Table 1

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

Table 2

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

I first want to select the regio in wicht Beetgum is, in this case regio 2. Then i want all the other 4PP in table 2 wich have the same regio (2). So the outcome of the query has to be 9044,9045

And here is a joined one :)

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'

Fiddle: http://sqlfiddle.com/#!2/347f3/3

Here's a really crappy query until someone gives you a fancy joined one (which you should then use)

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'
)

这应该做

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

Seems this is what you are looking for:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM