Subquery with MySql using INSERT - mysql

I'm trying to update the database, using a script where the ID of a user isn't readily known, so I'm using a subquery to have mysql find the user id (for the posteruserid value). This is the SQL query i'm using:
INSERT INTO `thread` (`title`, `forumid`, `open`, `replycount`,
`postercount`, `postusername`, `postuserid`, `lastposter`,
`dateline`, `visible`, `keywords`)
SELECT 'IN', 2, 1, 0, 1, 'lemons', `userid` FROM `user`
WHERE `username` = 'lemons', 'lemons', 1375768440, 1, 'IN';
I'm getting a syntax error from the above SQL, and I can't figure out what I'm doing wrong.
EDIT because of the mismatched column name, I tried using an alias, which still doesn't work
INSERT INTO `thread` (`title`, `forumid`, `open`, `replycount`,
`postercount`, `postusername`, `postuserid`, `lastposter`,
`dateline`, `visible`, `keywords`)
SELECT 'IN', 2, 1, 0, 1, 'lemons',
`userid` AS `postuserid` FROM `user` WHERE `username` = 'lemons',
'lemons', 1375768440, 1, 'IN';

column mismatch in insert and select query..column should be same where you are going to insert and from where you are fetching data.

You specify to insert values of 11 columns, but in your SELECT statement, you are providing only 7 values. Please provide the value for lastposter,dateline,visible, and keywords.

Related

mysql - insert multiple values for single column

I want to insert data into MySQL with multiple values in one field and remaining fields contains only one value.
I have tried below query
INSERT INTO assessment_training(
PARENT_SLNO
RNO
TRAINING_CATEGORY
TRAINING_NAME
)
VALUES (
9,
1,
'Technical',
(1,7)
);
Error #1241
`INSERT INTO assessment_training(PARENT_SLNO,RNO,TRAINING_CATEGORY,TRAINING_NAME) VALUES (9,1,'Technical',(1,7)) Error Code: 1241. Operand should contain 1 column(s)`
You can use CONCAT()
INSERT INTO assessment_training(
PARENT_SLNO,
RNO,
TRAINING_CATEGORY,
TRAINING_NAME
)
VALUES (
9,
1,
'Technical',
CONCAT("1", ",", "7")
);

Not have Subquery,But the mysql throw Subquery return more than 1 row

A standard insert MySQL query without any Subquery, but the MySQL tells me
Subquery return more than 1 row
INSERT INTO
db_novelV2.tbl_saler_todo
(
is_drive, customer_type, operator_id, STATUS, remark,
update_dt, receive_saler, src_id, come_dt, has_give_present,
TYPE, service_id, src_type, allot_saler, has_car_shuttle,
customer_id, session_id, arrive_dt, creater_id, leave_dt,
collector_id, store_id, allot_dt, add_dt
)
VALUES
(0, 0, 528, 0, '',NULL, 307,0, NOW(), 0, 1, 352,0,307, 0, 243465,2993333,NOW(), 528, NULL, 0,4, NOW(), NOW());
Check whether you have any INSERT triggers on your table, If so, disable any triggers before running your INSERT statement.

Mysql Insert record if not Exists

I have the following query
INSERT INTO `title_servicemetadatafielddefinition` (`service_id`, `field`, `behavior`, `alt_label`, `localizable`, `custom_type`, `required`, `max_length`, `help_text`)
VALUES (319, 'custom10', 'overridable', 'Rental Period', False, 'short_text', False, NULL, '24 hour;48 hour;72 hour;1 week;30 day;3 month;6 month;1 year')
WHERE NOT EXISTS ( SELECT * FROM `title_servicemetadatafielddefinition` WHERE `service_id` = 319 and `field` = 'custom10' ) LIMIT 1;
Error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS ( SELECT * FROM title_servicemetadatafielddefinition WHERE `s' at line 1
and was failing when trying to execute, can't able to figure out what syntax was wrong
Below query will insert if row does not exist and ignore if already exist but make sure that service_id here should be either primary key or unique key.
INSERT IGNORE INTO `title_servicemetadatafielddefinition` (`service_id`, `field`, `behavior`, `alt_label`, `localizable`, `custom_type`, `required`, `max_length`, `help_text`)
VALUES (319, 'custom10', 'overridable', 'Rental Period', False, 'short_text', False, NULL, '24 hour;48 hour;72 hour;1 week;30 day;3 month;6 month;1 year')
You Wrote 'Limit' in INSERT STATEMENT. I think, Limit should come in SELECT Statement.
INSERT INTO `title_servicemetadatafielddefinition` (`service_id`, `field`, `behavior`, `alt_label`, `localizable`, `custom_type`, `required`, `max_length`, `help_text`)
VALUES (319, 'custom10', 'overridable', 'Rental Period', False, 'short_text', False, NULL, '24 hour;48 hour;72 hour;1 week;30 day;3 month;6 month;1 year')
WHERE NOT EXISTS ( SELECT * FROM `title_servicemetadatafielddefinition` WHERE `service_id` = 319 and `field` = 'custom10' LIMIT 1);
Use "LIMIT" in a MySQL "INSERT"?
Try this:
INSERT INTO `title_servicemetadatafielddefinition` (`service_id`, `field`, `behavior`, `alt_label`, `localizable`, `custom_type`, `required`, `max_length`, `help_text`)
SELECT 319, 'custom10', 'overridable', 'Rental Period', False, 'short_text', False, NULL, '24 hour;48 hour;72 hour;1 week;30 day;3 month;6 month;1 year'
FROM (SELECT 1) x
LEFT JOIN `title_servicemetadatafielddefinition` t
ON t.`service_id` = 319 and t.`field` = 'custom10'
WHERE t.service_id IS NULL

MySQL. Counting just a part of my column value

I have a question relating tables in MySQL. To understand this better I'd rather show you. I have the following table:
CREATE TABLE IF NOT EXISTS `tip_masina` (
`id_tip` int(11) NOT NULL AUTO_INCREMENT,
`marca` varchar(40) NOT NULL,
`pret` int(11) NOT NULL,
PRIMARY KEY (`id_tip`),
UNIQUE KEY `marca` (`marca`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;
INSERT INTO `tip_masina` (`id_tip`, `marca`, `pret`) VALUES
(1, 'Chevrolet Impala', 8000),
(2, 'Chevrolet Camaro', 10000),
(3, 'Chevrolet Tahoe', 13000),
(4, 'Chevrolet Suburban', 12500),
(5, 'Chevrolet Cobalt', 4000),
(6, 'Dodge Charger', 14000),
(7, 'Dodge Avenger', 9000),
(8, 'Dodge Challenger', 6500),
(9, 'Dodge Dart', 3500),
(10, 'Dodge Durango', 3000),
(11, 'Ford Mustang', 7500),
(12, 'Ford Crown Victoria', 5000),
(13, 'Ford Focus', 4300),
(14, 'Ford Fiesta', 3700),
(15, 'Ford Escort', 1000);
What I want out of this table is to display the vehicle type and the number of vehicles, like:
marca | no_of_vehicles
Chevrolet 5
Dodge 5
Ford 5
Is there any way to do this without splitting the column marca in two columns?
Here is an easy way, using substring_index():
select substring_index(marca, ' ', 1) as marca, count(*)
from tip_masina
group by substring_index(marca, ' ', 1);
It might be better to split 'marca' into two columns so that it would be easier to find what you want. You won't need any special functions then (as e.g. substring_index).
EDIT:
You can use following code:
EDIT2:
Now it works (tested on mysql workbench with your queries creating table):
START TRANSACTION;
ALTER TABLE tip_masina ADD model VARCHAR(60) AFTER marca;
ALTER TABLE tip_masina CHANGE marca company VARCHAR(60);
UPDATE tip_masina SET model = SUBSTRING_INDEX(company, ' ', -1);
ALTER TABLE tip_masina DROP INDEX marca;
UPDATE tip_masina SET company = SUBSTRING_INDEX(company, ' ', 1);
SELECT * FROM tip_masina;

mysql: write query with if in where part

i have this table:
(`id`, `name`, `type`, `price`)
(1, 'cats', 1, 12.25),
(2, 'dogs', 0, 11.35),
(3, 'house', 1, 7.25),
(4, 'cats2', 2, 5.26);
I need select all data, but if type is 1, i need get items witch price is more than 10.
I create this query:
SELECT *
FROM `items`
WHERE IF(TYPE = "1", price > 10, 1 = 1)
Works well, but maybe possible write much smarter or in other way?
Maybe don't need "1 = 1"?.
I would like to know your advice, thanks
Your 1=1 is senseless, but your IF is not. You can use just 1:
SELECT *
FROM `items`
WHERE IF(TYPE = "1", price > 10, 1)
-since MySQL evaluates expression as bool (actually, int) - and so 1 means 'true'.
But on the other hand, there's logic equivalent for your condition:
SELECT *
FROM `items`
WHERE `price`>10 OR `type`!="1"
However, I've faced such case in another question and, after some researching, I've discovered that IF is faster, even if it looks more complicated.