问题
I have two queries that are working individually but when I attempt to combine them I am getting an error saying: "ERROR: missing FROM-clause entry for Table "A". The purpose of the queries is to look at the combined results of two tables which have a JSONB column in the format ["tag1","tag2","tag3"] with column name TAGS. Individually both queries work but when I attempt to combine them I get the error. I must be missing something but I've tried several approaches to no avail. Any idea how to resolve this issue? The result should be a distinct list of tags that match the query with a wildcard at the end. Below are the queries and the combination of them. I am using PostgreSQL 9.5.3
final Field<String> value = field(name("A", "value"), String.class);
final Table<Record1<String>> c1 = sql.dsl()
.selectDistinct(value)
.from(CAMPAIGN,lateral(table("jsonb_array_elements_text({0})", CAMPAIGN.TAGS)).as("A"))
.where(CAMPAIGN.STORE_KEY.equal(campaign.getStoreKey()))
.and(CAMPAIGN.CAMPAIGN_KEY.notEqual(campaignKey))
.and(value.like(search + "%%"))
.asTable("c1");
final Table<Record1<String>> c2 = sql.dsl()
.selectDistinct(value)
.from(STOREFRONT, lateral(table("jsonb_array_elements_text({0})", STOREFRONT.TAGS)).as("A"))
.where(STOREFRONT.STORE_KEY.equal(campaign.getStoreKey()))
.and(value.like(search + "%%"))
.asTable("c2");
final Result<Record1<String>> result = sql.dsl()
.selectDistinct(value)
.from(c1, c2)
.limit(30)
.fetch();
回答1:
You need to use a Union. Try this (don't have a workspace with jooq to test, but something like this should work):
final Field<String> value = field(name("A", "value"), String.class);
final Select<Record1<String>> c1 = sql.dsl()
.selectDistinct(value)
.from(CAMPAIGN,lateral(table("jsonb_array_elements_text({0})", CAMPAIGN.TAGS)).as("A"))
.where(CAMPAIGN.STORE_KEY.equal(campaign.getStoreKey()))
.and(CAMPAIGN.CAMPAIGN_KEY.notEqual(campaignKey))
.and(value.like(search + "%%"));
final Select<Record1<String>> c2 = sql.dsl()
.selectDistinct(value)
.from(STOREFRONT, lateral(table("jsonb_array_elements_text({0})", STOREFRONT.TAGS)).as("A"))
.where(STOREFRONT.STORE_KEY.equal(campaign.getStoreKey()))
.and(value.like(search + "%%"));
final Result<Record1<String>> result = sql.dsl()
.selectFrom(c1.asTable())
.union(c2)
.limit(30)
.fetch();
来源:https://stackoverflow.com/questions/39172848/jooq-combination-of-two-working-queries-failing-with-from-clause-error