从 X 和 Y 表中分割名称

问题描述 投票:0回答:1
CREATE TABLE x 
(
    name varchar(20), 
    email varchar(20), 
    order_id int 
);

INSERT INTO x 
VALUES ('Rahul Kada', '[email protected]', 123),
       ('Raj V', '[email protected]', 23),
       ('R V', '[email protected]', 3),
       ('N V', '[email protected]', 2);

CREATE TABLE y 
( 
    name varchar(20), 
    company_name varchar(20), 
    location varchar(20) 
);

INSERT INTO y 
VALUES ('Rahul Kada', 'x', 'IN'),
       ('Raj V', 'D', 'UK'),
       ('R V', 'A', 'USA'),
       ('N V', 'M', 'DE');

SELECT 
    name, 
    SUBSTR(name, 1, INSTR(name, ' ') - 1) AS first_name,
    SUBSTR(name, INSTR(name, ' ') + 1) AS last_name 
FROM x;

SELECT 
    name,
    SUBSTR(name, 1, INSTR(name, ' ') - 1) AS first_name,
    SUBSTR(name, INSTR(name, ' ') + 1) AS last_name 
FROM y;

SELECT DISTINCT
    a.first_name, a.last_name, a.email, a.order_id,
    p.company_name, p.location 
FROM 
    x AS a 
LEFT JOIN 
    y AS p ON p.first_name = a.first_name 
           OR p.last_name = a.last_name;

我创建了 2 个表,我想将 X 和 Y 表中的名称拆分为

First_name
Last_name
,然后左连接两个表

sql sqlite
1个回答
0
投票
try this below, 
SELECT DISTINCT
    a.first_name, a.last_name, a.email, a.order_id,
    p.company_name, p.location 
FROM 
    (SELECT 
        name, 
        SUBSTR(name, 1, INSTR(name, ' ') - 1) AS first_name,
        SUBSTR(name, INSTR(name, ' ') + 1) AS last_name,
        email,
        order_id
     FROM x) AS a 
LEFT JOIN 
    (SELECT 
        name, 
        SUBSTR(name, 1, INSTR(name, ' ') - 1) AS first_name,
        SUBSTR(name, INSTR(name, ' ') + 1) AS last_name,
        company_name,
        location
     FROM y) AS p 
ON p.first_name = a.first_name AND p.last_name = a.last_name;
© www.soinside.com 2019 - 2024. All rights reserved.