@@ -23,6 +23,10 @@ public class Select implements Query {
2323 * A list of joins that generates multiple JOIN clauses.
2424 */
2525 private final List <Join > joins = new ArrayList <>();
26+ /**
27+ * A list of conditions from subselects
28+ */
29+ private final List <Condition > subselectConditions = new ArrayList <>();
2630 /**
2731 * True if SELECT DISTINCT shall be used
2832 */
@@ -37,6 +41,10 @@ public class Select implements Query {
3741 private Condition condition ;
3842 private OrderBy orderBy ;
3943 private GroupBy groupBy ;
44+ /**
45+ * This may contain conditions from unin used as subselect
46+ */
47+ private final List <ValueBinding > union = new ArrayList <>();
4048
4149
4250 /**
@@ -159,6 +167,12 @@ public TableSelectedPhase from(final Query subquery, final String alias) {
159167 .concat (" ) AS " )
160168 .concat (alias );
161169
170+ if (subquery instanceof ConditionsBuiltPhase ) {
171+ this .subselectConditions .add (((ConditionsBuiltPhase ) subquery ).getSelect ().condition );
172+ } else if (subquery instanceof ValueBinding ) {
173+ this .union .add ((ValueBinding ) subquery );
174+ }
175+
162176 return new TableSelectedPhase ();
163177 }
164178
@@ -175,7 +189,8 @@ public String toSql() {
175189 .append (this .distinct ? "DISTINCT " : "" )
176190 .append (getColumns ())
177191 .append (" FROM " )
178- .append (this .source );
192+ .append (this .source )
193+ ;
179194
180195 if (!this .joins .isEmpty ()) {
181196 for (final var join : this .joins ) {
@@ -221,15 +236,22 @@ private GroupByPhase groupBy(final Column... groupByColumns) {
221236
222237
223238 private ValueConstructor toValuesInternal () {
224- if (Select .this .condition == null && Select .this .joins .isEmpty ()) {
225- return new ValueConstructor ();
226- }
227-
228239 final var values = new ValueConstructor ();
229240
230241 Select .this .joins .stream ()
231242 .map (Join ::toValues )
232- .forEach (values ::add );
243+ .forEach (values ::add )
244+ ;
245+
246+ Select .this .subselectConditions .stream ()
247+ .map (Condition ::getValues )
248+ .forEach (values ::add )
249+ ;
250+
251+ Select .this .union .stream ()
252+ .map (ValueBinding ::toValues )
253+ .forEach (values ::add )
254+ ;
233255
234256 if (this .condition != null ) {
235257 values .add (Select .this .condition .getValues ());
@@ -366,6 +388,11 @@ public ValueConstructor toValues() {
366388 }
367389
368390
391+ Select getSelect () {
392+ return Select .this ;
393+ }
394+
395+
369396 /**
370397 * Adds an order by clause to the statement.
371398 *
@@ -381,6 +408,11 @@ public OrderByPhase orderBy(final Column... columns) {
381408 public GroupByPhase groupBy (final Column ... columns ) {
382409 return Select .this .groupBy (columns );
383410 }
411+
412+
413+ public Union union (final ConditionsBuiltPhase otherSelect ) {
414+ return Union .of (this , otherSelect );
415+ }
384416 }
385417
386418 /**
0 commit comments