【问题标题】:SQL join with the same table with different selectSQL join 与同一个表不同的选择
【发布时间】:2020-08-20 00:30:10
【问题描述】:

我有一个包含 col1-col10 列的表 tablename。 并非每一行都填充了 col4,但每一行都填充了 col1、col2、col3。 我想在 col4 满足条件时获取所有 {col1, col2, col3} 元组,然后从表名中获取与元组 {col1, col2, col3} 匹配的所有行。

我不确定我应该使用内连接还是左连接或其他方式? (我认为内连接和左连接都应该给我相同的结果) 下面的查询给了我一个语法错误“不匹配的输入 AS”。编写此查询的正确方法是什么?

select col1, col2, col3
from tablename 
where col4 >= 1000 AS A
INNER JOIN
(select *
FROM tablename) AS B
ON A.col1 = B.col1 AND A.col2 = B.col2 A.col3 = B.col3

【问题讨论】:

    标签: mysql sql join subquery where-clause


    【解决方案1】:

    你可以使用exists:

    select t.*
    from mytable t
    where exists (
        select 1
        from mytable t1
        where 
            t1.col1 = t.col1 
            and t1.col2 = t.col2 
            and t1.col3 = t.col3 
            and t1.col4 >= 1000
    )
    

    【讨论】:

    • 这个查询中select 1是什么意思?
    • @user1745995: exists 只是检查子查询是否返回某些行(无论内容如何),因此我们不需要它返回某些内容 - 因此是 select 1。这只是一个约定,你可以使用select *select 0,它不会改变结果。
    • 这是连接等价物吗:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2020-09-30
    • 2013-06-02
    相关资源
    最近更新 更多