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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100