简体   繁体   中英

MySQL combine rows from multiple tables into on row

I'm trying to combine two columns from two different tables in my database into one.

cust_tbl (table 1):

JL_JOB_NO | 
-----------
1         |  
2         |

projects (table 2) :

prjID     | 
-----------
3         |  
4         |

I'd like my output to be:

new       | 
-----------
1         |  
2         |
3         |
4         |

I tried:

SELECT 'JL_JOB_NO' AS 'new'
FROM 'cust_tbl'
UNION
SELECT 'prjID' as 'new'
FROM 'projects';

Use backticks (`) instead of single quotes (or just remove them):

Try this:

SELECT `JL_JOB_NO` AS `new`
FROM `cust_tbl`
UNION
SELECT `prjID` as `new`
FROM `projects`;

Or just:

SELECT JL_JOB_NO AS new
FROM cust_tbl
UNION
SELECT prjID as new
FROM projects;

Side note: Back ticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set it is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.

Back ticks are necessary for situations like the following:

SELECT id, `my name`, `another field` , `field,with,comma`

而不是'(单引号)使用`(反引号)或删除'(单引号)

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.

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