[英]Filter and Join tables in MY SQL
我有两个表Table1和Table2在表1列中,移动设备具有多个移动电话号码条目。 我想从table1中获得那些重复的手机号码的ID,并在table2中(其中clientId = table1.id)搜索table1的ID。
我尝试了以下SQL代码以获取重复的手机号码的ID
SELECT id FROM table1 GROUP BY mobile HAVING COUNT(*) > 1
然后我尝试将值输入到新的数组中,其中table1.id = table2.clientId
foreach ($table1data as $key) {
$items[] = \Yii::$app->db->createCommand("
SELECT clientId
FROM table2
WHERE clientId = :cid
")
->bindValue(':cid',$key['id'])
->queryAll();
}
如果table1 (id)
具有相同的值,则可以将INNER JOIN
与EXISTS
:
select t2.*
from table2 t2 inner join
table1 t1
on t1.id = t2.clientId
where not exists (select 1 from table1 t11 where t11.mobile = t1.mobile and t11.id <> t.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.