简体   繁体   English

MySQL查询WHERE x和是否设置y

[英]MySQL query WHERE x and if set y

I've been working on a project at work and I need data from two tables. 我一直在工作一个项目,我需要两个表中的数据。 I'm no expert on MySQL queries, but I got this far: 我不是MySQL查询方面的专家,但是我已经做到了:

SELECT *
FROM `p_list` AS pl
JOIN `employee` AS em
WHERE em.id =10
AND pl.employee_id =10

It works fine when there is a pl.employee_id, but returns o result where there isn't. 当有一个pl.employee_id时,它工作正常,但在没有的情况下返回结果。 It makes sense, but I don't know how i can get it to return where em.id=10 and if pl.employee_id is set. 这是有道理的,但我不知道如何获取返回em.id = 10的位置以及是否设置了pl.employee_id的信息。

I'm about to give up and just run two queries and let PHP do the dirty work. 我要放弃,只运行两个查询,然后让PHP做脏事。

Try this, use LEFT JOIN 试试这个,使用LEFT JOIN

SELECT *
FROM   `p_list` AS pl
       LEFT JOIN `employee` AS em
          ON em.id = pl.employee_ID
WHERE  em.id = 10

Basically, what you are doing now is an INNER JOIN . 基本上,您现在正在做的是INNER JOIN INNER JOIN is different from LEFT JOIN ( which is what you need ). INNER JOINLEFT JOIN这是您需要的 )不同。 INNER JOIN only returns result if a record specified in the join condition has atleast one match on the other table. INNER JOIN仅在INNER JOIN条件中指定的记录在另一张表上至少有一个匹配项时才返回结果。 LEFT JOIN , on the other hand , returns all rows specified on the LEFT table whether it has a match or none match on the other table. 另一方面LEFT JOIN返回在LEFT表上指定的所有行,无论该表在另一个表上是否匹配。

You can use a left join to do this: 您可以使用左联接执行此操作:

SELECT *
FROM `p_list` AS pl
LEFT JOIN `employee` AS em ON em.id = pl.employee_id
WHERE em.id =10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM