如何编写将返回具有空字段的行的SQL查询?

时间:2016-05-23 23:56:17

标签: mysql

我想编写一个输出所有行的查询,包括其中包含空字段的行。但我的查询只输出包含所有非空字段的行。

这就是我的意思。

所以这些是我的桌子 表1:赞助商 enter image description here

表2:联系方式 enter image description here

这是我的疑问:

select from Subject_mark on table_1 ranged from table_2 

这是输出: enter image description here

我希望输出显示所有3个赞助商,如下所示: enter image description here

3 个答案:

答案 0 :(得分:0)

SELECT   s.sponsor_name, s.sub_name, SUM(s.amount), 
         COUNT(s.id), c.contact_name, c.tel
FROM     sponsor as s, contact as c
WHERE (s.id = c.sponsor_id) and (c.is_primary = 1)
GROUP BY sponsor_name, sub_name

应该最有可能阅读:

SELECT   s.sponsor_name, s.sub_name, SUM(s.amount), 
         COUNT(s.id), c.contact_name, c.tel
FROM     sponsor as s
LEFT JOIN contact as c ON (s.id = c.sponsor_id) and (c.is_primary = 1)
GROUP BY sponsor_name, sub_name

LEFT JOIN注意领先的表格数据,在本例中赞助商用于保存的行。

答案 1 :(得分:0)

这是因为您正在执行INNER JOIN,这会丢弃不匹配的行。您需要使用LEFT JOIN

SELECT   
    s.sponsor_name, 
    s.sub_name, 
    SUM(s.amount), 
    COUNT(s.id),
    c.contact_name,
    COALESCE(c.tel, 'N/A') AS tel
FROM  sponsor AS s
LEFT JOIN contact AS c
    ON  s.id = c.sponsor_id
    AND c.is_primary = 1
GROUP BY s.sponsor_name, s.sub_name

此外,您应该使用显式JOIN语法而不是旧式语法。

答案 2 :(得分:0)

SELECT   s.sponsor_name, s.sub_name, SUM(s.amount), 
         COUNT(s.id), c.contact_name, c.tel
FROM     sponsor as s
Left join contact c on  (s.id = c.sponsor_id) and (c.is_primary = 1)

WHERE (c.sponsor_id is null)
GROUP BY sponsor_name, sub_name

试试这个。或者,如果它不正常,则尝试编写sql,通过null

进行检查