当列为NULL时如何获取此查询?

时间:2019-04-02 23:19:29

标签: mysql sql

我正在尝试执行此查询以获取所有用户,组和电子邮件的列表,但是我的问题是,当用户与任何组都不相关时,所以radcheck.id_group列= NULL,但是我仍然要列出它。

ENDPOINT_URL = 'https://example.com'
headers = {'Api-key': '123abc'}

import threading
with open("student.csv", "r") as csv_ledger:
    r = csv.DictReader(csv_ledger)
    data = [dict(d) for d in r ]
    groups = {}

    for k, g in groupby(data, lambda r: (r['name'])):
        #My data mapping
        t = threading.Thread(target=requests.post,
                             args=(ENDPOINT_URL, groups, headers=headers))
        t.setDaemon(True)
        t.start()

如何正确书写?

2 个答案:

答案 0 :(得分:1)

使用显式LEFT JOIN

SELECT 
    r.username AS username, 
    g.name AS groupname, 
    g.id as gid, 
    u.email
FROM useremail u
LEFT JOIN radcheck r ON r.username = u.username
LEFT JOIN group g ON g.id = r.id_group

使用表别名通常也是一个好习惯:使用表别名可以使查询更易于阅读和维护(并在需要时允许自联接表...)。

答案 1 :(得分:1)

使用左联接:

SELECT 
  radcheck.username AS username, 
  group.name AS groupname, 
  group.id as gid, 
  useremail.email as email 
FROM useremail left join radcheck
ON radcheck.username = useremail.username
left join group
ON group.id = radcheck.id_group