【问题标题】:Filter and Join tables in MY SQLMYSQL 中的过滤和连接表
【发布时间】:2018-07-27 16:21:46
【问题描述】:

我有两个表 Table1 和 Table2 在表 1 列中,mobile 有多个 Mobile number 条目。 我想从table1中获取那些重复的手机号码的id,并在table2中搜索table1的id,其中clientId = 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();
    }

【问题讨论】:

标签: mysql sql yii2


【解决方案1】:

如果table1 (id) 具有相同的值,那么您可以将INNER JOINEXISTS 一起使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-26
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多