[英]MySQL select 1 of multiple rows with same field based on where clause
[英]Mysql select rows with same table not in where clause
我有2张桌子,像这样:
表格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中的区域,在这种情况下为区域2。然后,我希望表2中的所有其他4PP具有相同的区域(2)。 因此查询结果必须为9044,9045
这是一个加入的:)
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
这是一个非常糟糕的查询,直到有人给您看中了加入的查询(然后您应该使用)
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"))
似乎这是您要寻找的:
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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.