Table A (nothing is unique)
╔══════╦══════╦═══════════╦═══════════════╗
║ p_id ║ l_id ║ p_name ║ p_description ║
╠══════╬══════╬═══════════╬═══════════════╣
║ 212 ║ 1 ║ Ball ║ Red ║
║ 212 ║ 2 ║ Balle ║ Rouge ║
║ 301 ║ 1 ║ Horn name ║ Blue ║
╚══════╩══════╩═══════════╩═══════════════╝
Table B (p_id is unique)
╔══════╗
║ p_id ║
╠══════╣
║ 101 ║
║ 201 ║
║ 210 ║
║ 212 ║
║ 234 ║
║ 250 ║
║ 301 ║
║ 320 ║
╚══════╝
Wrt p_id, Table A is a subset of Table B (all p_id should exist in Table B) but Table A contains different data. Both tables contain a lot more columns that I'm not showing. For table A I'm only concerned with the p_id. For table BI want to eliminate duplicates based on l_id. There will always be an entry with l_id of 1 but there may or may not be others which should be discarded (ie. a simple WHERE l_id=1 should do).
The result should be a table that has every p_id of Table B (once) with every column of Table A. Most of the rows will have no data in those other columns, because they didn't exist in Table B. So I should have this, for example:
╔══════╦══════╦═══════════╦═══════════════╗
║ p_id ║ l_id ║ p_name ║ p_description ║
╠══════╬══════╬═══════════╬═══════════════╣
║ 101 ║ ║ ║ ║
║ 201 ║ ║ ║ ║
║ 210 ║ ║ ║ ║
║ 212 ║ 1 ║ Ball ║ Red ║
║ 234 ║ ║ ║ ║
║ 250 ║ ║ ║ ║
║ 301 ║ 1 ║ Horn name ║ Blue ║
║ 320 ║ ║ ║ ║
╚══════╩══════╩═══════════╩═══════════════╝
From your description, this sounds like a left join
:
select b.p_id, a.l_id, a.p_name, a.p_description
from b left join
a
on b.p_id = a.p_id and a.l_id = 1;
To get all rows from one table and the rows matching some condition from another you can use a left join
:
select b.p_id, a.l_id, a.p_name, a.p_description
from b
left join a on b.p_id = a.p_id and a.l_id = 1
This will get you everything from B with values for the columns in A matching the where condition. For those rows in B that doesn't have any matches you'll get null
values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.