Question

I have a DB table structure with around 6000 rows as given below:.

carrier|make|model

My need is to create an sql Query such that I can insert a Make-Model pair for all the carriers except few(say ATT, bell-mobility, virgin Canada and Warranty ATT).

How can I get this done?

Was it helpful?

Solution

INSERT INTO table_name (carrier, make, model)
SELECT DISTINCT carrier, "Samsung", "Galaxy S5"
FROM table_name
WHERE carrier NOT IN ( 'ATT', 'bell-mobility', 'virgin Canada', 'Warranty ATT' )

To add multiple new makes and models you can do:

INSERT INTO table_name (carrier, make, model)
SELECT a.carrier, b.make, b.model
FROM (SELECT DISTINCT carrier
      FROM table_name
      WHERE carrier NOT IN ( 'ATT', 'bell-mobility', 'virgin Canada', 'Warranty ATT' ) AS a
CROSS JOIN
    (SELECT "Samsung" AS make, "Galaxy 5" AS model
     UNION
     SELECT "Nokia" AS make, "Lumia" AS model
     ...
    ) AS b

BTW, this question suggests that you have a poor database design. You should have a table of carriers that lists all the carriers you know of, you shouldn't get it from the table that lists the makes and models for each carrier. This is an example of poor normalization, because if you ever stop supplying phones for some carrier, you'll totally forget that they exist.

OTHER TIPS

MYSQL iNSERT SYNTAX - http://dev.mysql.com/doc/refman/5.6/en/insert.html

If you're talking about PHP, take a look at this page: http://www.w3schools.com/php/php_mysql_insert.asp

EDIT:

A good solution can be found here.

And if you use the above solution, the result should be something like:

INSERT INTO table ("carrier", "make", "model") 
 SELECT DISTINCT carrier, make, model
 FROM `table2` AS o
 WHERE o.name NOT 
 IN ( "ATT", "bell-mobility", "virgin Canada", "Warranty ATT"  )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top