Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Where to place functions inside/outside a subquery? #244

Open
MrSwitch opened this issue Sep 15, 2022 · 1 comment
Open

Where to place functions inside/outside a subquery? #244

MrSwitch opened this issue Sep 15, 2022 · 1 comment

Comments

@MrSwitch
Copy link
Member

MrSwitch commented Sep 15, 2022

When using a function around a field value which points to another table it usually creates a subquery, but where should the function go, around the field within the subquery, or around the subquery?

For example...

e.g.

{
	"table": "members"
	"fields": [
		{
			"hasEmail": "IF(email.id, 'YES', 'NO')"
		}
	]
}

In most instances, Dare would create a subquery, so the query would look like...

SELECT name, (
	SELECT IF(id, "YES", "NO")
	FROM email
	WHERE email.member_id = members.id
	LIMIT 1
)
FROM members

Notice how the IF(...) is within the Subquery itself.

However if there is are no matches in the joining table the result will be NULL not "NO" - because the subquery returned zero rows. It needs at-least one empty row so the IF condition can say "No".

What was really meant was...

SELECT name, IF((
	SELECT id
	FROM email
	WHERE email.member_id = members.id
	LIMIT 1
),  "YES", "NO")
FROM members

Of course some functions are aggregates like MAX, COUNT, GROUP_CONCAT, ... these will always need to be defined within the subquery to work. They even have the affect of aggregating the results of a query within mysql.

@MrSwitch
Copy link
Member Author

MrSwitch commented Oct 8, 2022

Workaround: The above can be worked around using an aggregated function, because they force a single row (except when there is a groupby)

e.g. using COUNT(): IF(COUNT(email.id), 'YES', 'NO')

{
	"table": "members"
	"fields": [
		{
			"hasEmail": "IF(COUNT(email.id), 'YES', 'NO')"
		}
	]
}

@MrSwitch MrSwitch changed the title Where to place functions within a subquery field value Where to place functions inside/outside a subquery? Oct 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant