How to use a join to query two tables and retrieve all rows from one and related rows from another?

Simplified, for example, I have two tables, groupsand items.

items (
    id,
    groupId,
    title
)

groups (
    id,
    groupTitle,
    externalURL
)

The regular query that I make looks something like this:

SELECT
    i.`id`,
    i.`title`,
    g.`id` as 'groupId',
    g.`groupTitle`,
    g.`externalURL`
FROM
    items i INNER JOIN groups g ON (i.`groupId` = g.`id`)

However, I need to change this now because all the groups that indicate externalURLwill not have the corresponding records in the table items(since they are stored externally). Is it possible to make some kind of connection so that the result looks like this:

items:
id    title    groupId
----------------------
1     Item 1   1
2     Item 2   1

groups
id    groupTitle    externalURL
-------------------------------
1     Group 1       NULL
2     Group 2       something
3     Group 3       NULL

Query output:
id    title    groupId    groupTitle    externalURL
---------------------------------------------------
1     Item 1   1          Group 1       NULL
2     Item 2   1          Group 1       NULL
NULL  NULL     2          Group 2       something

-- note that group 3 didn't show up because it had no items OR externalURL

Is this possible in a single SQL query?

+3
source share
1 answer

, : , , . NULL .

, WHERE.

SELECT
    i.`id`,
    i.`title`,
    g.`id` as 'groupId',
    g.`groupTitle`,
    g.`externalURL`
FROM
    items i RIGHT OUTER JOIN groups g ON (i.`groupId` = g.`id`)
WHERE i.`id` IS NOT NULL OR g.`externalURL` IS NOT NULL;

i.id g.externalURL NULL, .

+11

Source: https://habr.com/ru/post/1699696/


All Articles