kellerkindt kellerkindt - 1 month ago 9
MySQL Question

JDBC (My)SQL only fetch cell data if flag is set

I got a table with a lot of content and a column with a flag. Sometimes I want to load all the content, and sometimes I dont - for simplification of this quiestion, I want to load the content depending only on the flag.

Is there a way to load the content depending on the flags state?

Think of the table like this:

+--+--------------+-----+
|id|content |flag |
+--+--------------+-----+
| 0| lots of text |false|
| 1| lots of text |false|
| 2| lots of text | true|
+--+--------------+-----+


I want my ResultSet to be filled like this:

+--+--------------+-----+
|id|content |flag |
+--+--------------+-----+
| 0| NULL |false| <- only content null, otherwise full row
| 1| NULL |false| <- only content null, otherwise full row
| 2| lots of text | true|
+--+--------------+-----+


How does the SQL query look like? Is this even possible?

Answer

You could use the WHERE as others have mentioned or the IF function, e.g.:

SELECT t.id, IF(t.flag, t.content, NULL), t.flag from table t