duanpeng1532 2014-08-08 17:39
浏览 225
已采纳

MySQL加入以在WHERE语句中包含不匹配的记录

I need to output data from two table if it exists.

I want to select all records in Table 1 for display in a PHP Recordset using a dynamic html table. I also need to display some data from Table 2 if it exists. My existing query is not selecting all the data I need from the two tables.

Table 1

EmpNum     FirstName   EmpType
541        Robert      88
222        Samuel      88
521        Anthony     88

Table 2

ID   SecretKey     NickName
541  6565          Bob
222  9999          Sam

I also want to "join" this data with another table that may or may not have matches. This is throwing off my results.

SELECT Table1.EmpNum, Table1.FirstName, Table2.ID, Table2.SecretKey, Table2.NickName FROM Table1, Table2 WHERE Table1.EmpNum=Table2.ID AND Table1.EmpType = '88'

This query is omitting the EmpNum 521 from the tabular data because my WHERE clause does not find a match.

I'd like to have all the records display from Table 1 and then append data from Table 2 if a match exists.

Example DESIRED output:

EmpNum     FirstName   EmpType     SecretKey     NickName
541        Robert      88          6565          Bob
222        Samuel      88          9999          Sam
521        Anthony     88

In this example above Anthony is still displayed even though he has not records in Table 2.

How do I alter my join to achieve this.

  • 写回答

2条回答 默认 最新

  • doubi7496 2014-08-08 17:41
    关注

    Use an outer join -

    SELECT Table1.EmpNum, Table1.FirstName, Table2.ID, Table2.SecretKey, Table2.NickName 
    FROM Table1
    LEFT OUTER JOIN Table2 
    ON Table1.EmpNum = Table2.ID
    WHERE Table1.EmpType = '88'
    

    You can continue to outer join additional tables as you need, getting all of the data from the first table and then only matching data from the subsequent tables.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试