简体   繁体   中英

MySQL create table containing values from a column in another table

Lets say I have a table tilistings with a dozen columns, and about 2,000 rows there is one column cityname that has probably 50 different values in it. What I want to do, is search through the tilistings and create another table that just contains the 50 different values from cityname without duplicating any names....basically if cityname had the values a,b,a,c,b,b,d,a,a,d,d,c I would only want the new table to contain a,b,c . Is there a pre-built MySQL function to do so? Otherwise, just point me in the right direction to do this with PHP. I can create the table, just looking to populate it.

Or do it all in SQL, if you already have created a table named cities with a single column cityname :

INSERT INTO `cities` (`cityname`)
SELECT DISTINCT `cityname` FROM `tilistings`;

Or crate the table from the SELECT :

CREATE TABLE `cities`
SELECT DISTINCT `cityname` FROM `tilistings`;

You can get the unique city names by performing the following query:

SELECT DISTINCT cityname FROM tilistings

Then loop through those and INSERT them into your new table with PHP or INSERT INTO ... SELECT .

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