簡體   English   中英

根據兩個表選擇記錄,其中一個表中的一列使用SQL從另一個表列的記錄開始

[英]Select records based on two tables where one column in one table starts with the records from another tables column using SQL

我有一個包含作業號前綴的表。 另一個表包含完整的作業編號以及其他幾個數據列。 我想使用sql返回以下結果。

表格1

PfxJobNum
--------
001
006
024

表2

Id JobNum
--------
1 001aed
2 001bef
3 924bac
4 006aab
5 056bcb
6 084baa

結果

Id JobNum
--------
1 001aed
2 001bef
4 006aab

您可以嘗試使用exists .... like的子查詢exists .... like

SELECT * 
FROM Table2 t1
WHERE exists (
 select 1
 FROM Table1 t2
 WHERE t1.JobNum like  t2.PfxJobNum +'%'
)

sqlfiddle

或使用CONCAT

架構(MySQL v5.7)

create table Table1(
   PfxJobNum varchar(50)
);



INSERT INTO Table1 VALUES ('001');
INSERT INTO Table1 VALUES ('006');
INSERT INTO Table1 VALUES ('024');


create table Table2(
   Id INT,
   JobNum varchar(50)
);




INSERT INTO Table2 VALUES (1,'001aed');
INSERT INTO Table2 VALUES (2,'001bef');
INSERT INTO Table2 VALUES (3,'924bac');
INSERT INTO Table2 VALUES (4,'006aab');
INSERT INTO Table2 VALUES (5,'056bcb');

查詢#1

SELECT * 
FROM Table2 t1
WHERE exists (
 select 1
 FROM Table1 t2
 WHERE t1.JobNum like CONCAT(t2.PfxJobNum ,'%')
);

| Id  | JobNum |
| --- | ------ |
| 1   | 001aed |
| 2   | 001bef |
| 4   | 006aab |

查看DB小提琴

如果你的前綴總是相同的長度,我會建議:

select t2.*
from table2 t2
where exists (select 1
              from table1 t1
              where t1.PfxJobNum = left(t2.JobNum, 3)
             );

這是首選方法,因為它可以利用table1(PfxJobNum)上的索引。

並非所有數據庫都支持left() ; 在這種情況下, substr()substring()工作正常。

如果前綴的長度不同,那么使用like

select t2.*
from table2 t2
where exists (select 1
              from table1 t1
              where t2.JobNum like t1.PfxJobNum || '%'
            );

並非所有數據庫都使用標准|| 用於字符串連接。 在這些數據庫中,使用適當的運算符。

我能夠在MS Access和MySQL 5.7中使用它。 這和WHERE EXISTS(...什么區別WHERE EXISTS(...

SELECT *
FROM Table1, Table2
WHERE Left(Table2.JobNum,3)=Table1.PfxJobNum;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM