[英]SQL Query To Get All Records From One Table, Except A Specific Record, By Date, From Another Table
I am trying to SELECT records from two MySql tables. 我试图从两个MySql表中选择记录。 I would like all records from the first table excluding specific records, by date, from the second table. 我希望第一个表中的所有记录从第二个表中按日期排除特定记录。 For example: 例如:
Table1 T1id
, firstName
, LastName
表1 T1id
, firstName
, LastName
Table2 id
, T1id
, hours
, rate
, date
表2 id
, T1id
, hours
, rate
, date
T1id
is the link between the two tables, therefore when the tables are joined I would have T1id
, firstName
, lastName
, hours
, rate
, date
T1id
是两个表之间的链接,因此当表连接时,我会有T1id
, firstName
, lastName
, hours
, rate
, date
Let's say there is a record in Table2 with a date
of 2012-02-08. 假设表2中有一条记录,其date
为2012-02-08。 With one query, I need to select all records from Table1 , excluding the record from Table2 that has the date of 2012-02-08 . 使用一个查询,我需要从Table1中选择所有记录, 不包括Table2中具有日期2012-02-08的记录 。
I've tried a few variations of JOINS and UNIONS, however I either get all records, a bunch of duplicate records, or one record (ie Table2 date). 我尝试了JOINS和UNIONS的一些变体,但是我要么获得所有记录,一堆重复记录,要么记录一次(即Table2日期)。 I apologize, but I do not have a specific piece of code to include since nothing has worked for me. 我道歉,但我没有特定的代码片段,因为没有什么对我有用。
USE INNER JOIN
if you are sure that T1id exists in both tables: 如果您确定两个表中都存在T1id,请使用INNER JOIN
:
SELECT a.T1id,
a.FirstName,
a.LastName,
b.hours,
b.rate,
b.date
FROM table1 a INNER JOIN table2 b
ON a.T1id = b.T1id
WHERE b.date <> DATE('2012-02-08')
but if you want to get all T1id
from Table1 (which exists or does not exists in Table2 ) use LEFT JOIN
但是如果你想从Table1中获取所有T1id
(表2 中存在或不存在 ),请使用LEFT JOIN
SELECT a.T1id,
a.FirstName,
a.LastName,
b.hours,
b.rate,
b.date
FROM table1 a LEFT JOIN table2 b
ON a.T1id = b.T1id
WHERE b.date <> DATE('2012-02-08')
So many times this is typically done with a NOT EXISTS subquery, but subqueries can be big performance hits in larger tables... However, by doing a LEFT JOIN and looking for NULL is in essence, the same result 这么多次通常使用NOT EXISTS子查询来完成,但是子查询可以在较大的表中进行大的性能命中...但是,通过执行LEFT JOIN并且查找NULL本质上是相同的结果
select
t1.*
from
table1 t1
left join table2 t2
on t1.t2.t1id
AND t2.date = '2012-02-08'
where
t2.t1id IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.