dpt62283 2013-09-20 08:41
浏览 45
已采纳

php,mysql - 选择具有多个值的列的行

I have the following kind of setup (a bit oversimplified):

An array (php): array('a', 'b', 'c');

Table 1: id with values (1), (2), (3), (others).

Table 2: id, idT1,value with values (1, 1, 'a'), (2, 1, 'b'), (3, 1, 'c'), (4, 2, 'c'), (5, 77, 'w') (others).

I need to select rows from table 1, that have correspondent in table 2 with ALL the values in the array (in this case the row with id col = 1).

A way to do this would be something like (ignore possible typos pls)

 <?php
      $query = "SELECT * FROM `table1` WHERE `id` IN ";
      $subqr = "";
      foreach ($arr as $a) {
          if (!$subqr)
              $subqr = "(SELECT `idT1` FROM `table2` WHERE `value` = '$a')";
          else
              $subqr .= " AND `id` IN (SELECT `idT1` FROM `table2` WHERE `value` = '$a')";
      }

      ExecuteQuery($query.$subqr); // Where ExecuteQuery gets query as param.

Now my problem is that... I'm not exactly comfortable with the solution... I mean... a foreach that adds subqueries is likely not to be the best approach. If the array has 9999 elements... 9999 subqueries would just kill mysql. Also bear in mind that this is oversimplified.

Any other ideas how to do this?

  • 写回答

1条回答 默认 最新

  • donkey199024 2013-09-20 09:06
    关注

    Correct me if I'm wrong, you want to select all the records from Table 1 which has it's ID on Table 2 on field idT1. If that's the case you can try

    SELECT id
    FROM table1
    LEFT OUTER JOIN table2
    ON table1.id=table2.idT1;
    

    EDIT:

    SELECT * 
    FROM table1 
    INNER JOIN table2 
    ON table1.id=table2.idT1
    WHERE table2.value IN ('a','b','c')
    GROUP BY table1.id
    HAVING COUNT(DISTINCT table2.value) = 3
    

    so first, you need to use php implode the array for the line

    WHERE table2.value IN ('a','b','c')
    

    then php count for this line

    HAVING COUNT(DISTINCT table2.value) = 3
    

    that would replace 3

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c