[英]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.