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.
精彩评论