How might I write a MySQL query to achieve the desired result shown below?
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
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 ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.