如何查找具有所有其他列值的所有行

时间:2019-11-09 05:26:03

标签: mysql sql

我有两个这样的表:

Tb1
------------
col
1
2
3

Tb2
-----------
id name Tb1_col
1   a    1
2   a    2
3   b    1
4   a    3

现在,我想从name中获取所有Tb2个值,这些值具有col中所有的Tb1值。 对于此示例,我只期望a

4 个答案:

答案 0 :(得分:1)

一种方法是在JOIN上将Tb1_col的Tb2到Tb1,并检查给定name的不同值的数量与{ {1}}:

Tb1

输出

SELECT Tb2.name
FROM Tb2
JOIN Tb1 ON Tb1.col = Tb2.Tb1_col
GROUP BY Tb2.name
HAVING COUNT(DISTINCT Tb2.Tb1_col) = (SELECT COUNT(*) FROM Tb1)

Demo on dbfiddle

答案 1 :(得分:0)

不是很优雅的解决方案,但是...

SELECT distinct name from Tb2 as t1
WHERE NOT EXISTS (SELECT t2.col, t3.id
                  FROM Tb1 as t2 LEFT JOIN Tb2 as t3 ON t3.Tb1_col = t2.col
                                                     AND t3.name = t1.name
                  WHERE t3.id IS NULL);

答案 2 :(得分:0)

如果将tb1_col定义为外键(意味着所有值都是有效的引用),则可以简化尼克的答案:

SELECT Tb2.name
FROM Tb2
GROUP BY Tb2.name
HAVING COUNT(DISTINCT Tb2.Tb1_col) = (SELECT COUNT(*) FROM Tb1)

如果tb1_col从不重复给定名称,则使用:

HAVING COUNT(*) = (SELECT COUNT(*) FROM Tb1)

应该更加高效。

答案 3 :(得分:-1)

应该使用简单的左联接吗?

<?php 
    // Select all Data **********************/
    if(isset($_GET['getsection'])){
        $cls = $_POST['class_id'];
        $id = $_POST['id'];
        $sql_section = "select * from $tb_teacher_subject where t_class='$cls' and id='$id'";
        $res_section = mysqli_query($conn,$sql_section);
        if($res_section){
            while($row_sec = mysqli_fetch_assoc($res_section)){ 
                $sec = $row_sec['t_section'];
?>
                <option value="<?php echo $row_sec['t_section'] ?>"> 
                <?php
                $sql_clse = "select * from $tb_section where school_id='$school_id' and id='$sec'";
                $res_clse = mysqli_query($conn,$sql_clse);
                if($res_clse){
                    while($rows_clse = mysqli_fetch_assoc($res_clse)){
                        echo $rows_clse['t_section'];
                    }

                }  ?>
                </option>                
<?php
            }
        }
    }
?>