Skip to content

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

Description

@MrSwitch

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions