SQL AND不需要

时间:2018-06-25 14:11:34

标签: mysql

我的网站上显示一个表格,其中列出了项目列表。下面的SQL语句提取每个项目,并将### _ id列转换为另一个表中的### _ name。到目前为止一切顺利。

我的问题是,这需要填写项目表中一行中的所有字段。例如,如果项目行没有'proj_industry_id'的值,则该项目将根本不在此处显示。

我尝试删除WHERE语句中每个匹配项的“ AND”,并用逗号分隔,但会出错。

我还检查了SQL文档,但似乎找不到在那里的答案的方法。

有什么想法可以让我的语句在我有一个ID时仍然使ID与名称匹配,而在没有ID时仍显示记录吗?

谢谢!

$sql = "SELECT
    projects.*,
    engagement_types.eng_type_name AS eng_type,
    users.user_full_name AS username,
    industries.industry_name AS industry_name,
    categories.category_name AS category_name,
    geographies.geo_name AS geo_name,
    status.status_name AS status_name
FROM
    projects,
    engagement_types,
    users,
    industries,
    categories,
    geographies,
    status
WHERE
    projects.proj_eng_type_id = engagement_types.id
    AND projects.proj_lead_id = users.id
    AND projects.proj_industry_id = industries.id
    AND projects.proj_category_id = categories.id
    AND projects.proj_geo_id = geographies.id
    AND projects.proj_status_id = status.id
    AND projects.proj_geo_id = '$selected_geo_id'";

***** EDIT ******

这是下面使用多个左联接的解决方案中的最终正确代码!

SELECT
    projects.*,
    engagement_types.eng_type_name AS eng_type,
    users.user_full_name AS username,
    industries.industry_name AS industry_name,
    categories.category_name AS category_name,
    geographies.geo_name AS geo_name,
    status.status_name AS status_name
FROM 
    projects
LEFT JOIN engagement_types ON projects.proj_eng_type_id = engagement_types.id
LEFT JOIN users ON projects.proj_lead_id = users.id
LEFT JOIN industries ON projects.proj_industry_id = industries.id
LEFT JOIN categories ON projects.proj_category_id = categories.id
LEFT JOIN geographies ON projects.proj_geo_id = geographies.id
LEFT JOIN status ON projects.proj_status_id = status.id
GROUP BY
    proj_start_date 

1 个答案:

答案 0 :(得分:1)

像您这样的声音必须看“ LEFT JOIN” https://www.w3schools.com/sql/sql_join_left.asp 否则,您会错过绿色圆圈的左侧部分。