简体   繁体   English

如何编写一个MySQL查询,该查询返回一个临时列,该列包含有关与该行相关的项目是否在另一个表中的标志

[英]How to write a MySQL query that returns a temporary column containing flags for whether or not an item related to that row exists in another table

How might I write a MySQL query to achieve the desired result shown below? 我如何编写MySQL查询以达到如下所示的预期结果?

I have two tables: 我有两个表:

TABLE_USERS:

 ID | Name  |  ... 
--------------------
 1  | Ash   |
 2  | Tim   |
 3  | Jim   |
 4  | Jay   |
 5  | Tom   |


TABLE_FLAGS:

 ID | Reason |  ...
----------------------
 2  |  ??    |
 4  |  ...   |

I want to know how to write a query that yields a result with the following columns: 我想知道如何编写一个查询,并产生以下结果:

DESIRED RESULT:


 ID | Name  | Flagged
----------------------
 1  | Ash   |  false
 2  | Tim   |  true
 3  | Jim   |  false
 4  | Jay   |  true
 5  | Tom   |  false

I could do: 我可以做:

SELECT TABLE_USERS.ID, TABLE_USERS.NAME
FROM TABLE_USER

To get the first two columns, but I'm not sure how to get the last one... 要获得前两列,但我不确定如何获得最后一列...

The final column does not directly correspond to a column in one of the two tables; 最后一列不直接对应于两个表之一中的一列; instead for each row it returns true or false base on whether an entry for that rows id value exists in TABLE_FLAGS 而是根据TABLE_FLAGS中是否存在该行id值的条目,为每行返回true或false

Thanks 谢谢

   SELECT   tu.ID, 
            tu.NAME,
            CASE WHEN tf.ID IS NOT NULL THEN 'true' ELSE 'false' END AS Flagged
      FROM  TABLE_USER tu
            LEFT OUTER JOIN TABLE_FLAGS tf ON tu.ID = tf.ID

This will show your desired output: 这将显示您想要的输出:

SELECT tu.ID, tu.NAME,
       CASE WHEN tf.ID IS NOT NULL THEN 'true' ELSE 'false' END AS Flagged
  FROM TABLE_USER tu
       LEFT OUTER JOIN TABLE_FLAGS tf ON tu.ID = tf.ID ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 确定每一行是否存在于另一个MySQL表中 - Determining whether each row exists in another MySQL table MYSQL 查询检查 ID 是否存在并将列行值复制到另一个表相关的列名 - MYSQL query check if ID exist and copy column row values to another table related column names 如何在mysql中编写一个搜索查询,该查询匹配不同表中的列并从第一个表返回另一列? - How to write a search query in mysql which matches columns from different tables and returns another column from the first table? MySQL查询不存在于另一个表中 - MySQL query for not exists in another table 如何确定临时表是否存在 - How can I determine whether a temporary table exists 如果该项目已经存在,如何重写相同的mysql表行? - How to rewrite the same mysql table row if the item already exists? 链接URL取决于MySQL表中是否存在行 - Having a link URL dependent on whether or not a row exists in a MySQL table 查找MySQL表中是否存在匹配行的最有效方法 - Most efficient way to find whether matching row exists in MySQL table MySQL查询-对一个相关表求和-对另一个相关表进行计数 - MySQL Query - Sum one related table - Count another related table Mysql表行中的文本搜索,如果存在与命令相关的命令,则删除/更新 - Text Search in Mysql Table Row and Delete/Update if Exists related to command
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM