【问题标题】:How to select all from SQL query including subquery如何从 SQL 查询中全选,包括子查询
【发布时间】:2011-05-24 00:09:35
【问题描述】:

我想执行一个 mySQL 查询,该查询返回表中的所有结果,但如果它们对应于单独的查询,则有一个附加列具有“选定”值。例如

| name |
|------|
| a    |
| b    |
| c    |

当我执行查询“select * from table where name = 'a';”时,我希望能够返回以下内容;

| name | selected |
|------|----------|
| a    |  yes     |
| b    |          |
| c    |          |

也就是说,我也想知道哪些漏掉了。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:
    select *
        , selected = case
            when exists (
                select *
                from table2 t2
                where t2.field = t1.field
                    and ...etc.
            ) then 1 
            else 0
        end
    from table t1
    

    【讨论】:

      【解决方案2】:

      Where 子句限制您的行集,因此您只能获得名称为“a”的行。 要让它们全部加入受限表,或者使用 IF 而不使用 where:

      SELECT *, IF( name='a', 'yes', '') AS selected
      FROM table
      

      【讨论】:

      • +1 为给出的 SQL 提供最佳答案,但是 OP 的实际查询可能更复杂
      【解决方案3】:

      对我有用的是:

      select a.*
          , name = case
              when 
                 a.name = 'a'
               then 0 
              else 1
          end
      as selected
      from points as a
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 2013-01-25
        • 2020-10-04
        相关资源
        最近更新 更多