mysql add key does not work - mysql

I have this query:
SELECT adressid, adressname FROM kino_adressen WHERE city ='Seattle'
I wanted to create an index like this
ALTER TABLE <tablename> ADD KEY index_abc(adressid, adressname(40))
But when I then check it by using:
EXPLAIN SELECT adressid, adressname FROM kino_adressen WHERE city ='Seattle'
It says
type = ALL
possible keys = NULL
key = NULL
...rows = 106
Can anyone give some piece of advice how to do this properly ?
// edit:
Another problem I do not understand:
SELECT DISTINCT
titel,
regie,
darsteller,
filmbild,
kino_filme.filmid,
kino_filme.beschreibung,
fsk,
filmlaenge,
verleih,
sprachfassung
FROM
kino_filme
LEFT JOIN kino_terminefilme ON (
kino_terminefilme.filmid = kino_filme.filmid
)
LEFT JOIN kino_termine ON (
kino_terminefilme.terminid = kino_termine.terminid
)
LEFT JOIN kino_kinos ON (
kino_kinos.kinoid = kino_termine.kinoid
)
LEFT JOIN kino_adressen ON (
kino_adressen.adressid = kino_kinos.adressid
)
WHERE
kino_adressen.adressid = 32038
And the result is like:
Why is kino_termine not using any index ?
I set it to PK while creating and even added an index afterwards, but none of those helped.

You added an index on the address but use the city in the where clause. Add an index on the city then it will be used.

Related

Insert ROWS if not exists SQL

I want to insert rows that not exist in my table
INSERT INTO [Cop].[fact_capacidadOperativa] ([id_empleado],[id_proyecto],[id_rol],[id_categoria],[id_subCategoria],[id_portfolio]
,[id_programa],[horas],[horasPlan],[id_semanaAño],[id_torre])
/*SELECT * FROM [Cop].[timeSheet]*/
SELECT id_empleado,id_proyecto,id_rol,id_categoria,id_subCategoria,
id_portfolio,id_programa,[Cop].[timeSheet].horas,[Cop].[ListaEmpleados].horaPlan,
[Cop].[timeSheet].nroSemana+[Cop].[timeSheet].año AS id_semanaAño,id_torre FROM [Cop].[timeSheet]
JOIN [Cop].[ListaEmpleados]
ON [Cop].[timeSheet].nombre = [Cop].[ListaEmpleados].recurso
LEFT JOIN [Cop].[ListaProyectos]
ON [Cop].[timeSheet].[proyecto] = [Cop].[ListaProyectos].proyecto
JOIN [Cop].[dim_empleados]
ON [Cop].[timeSheet].nombre = [Cop].[dim_empleados].empleado
LEFT JOIN [Cop].[dim_proyectos]
ON [Cop].[timeSheet].proyecto = [Cop].[dim_proyectos].proyecto
JOIN [Cop].[dim_roles]
ON [Cop].[ListaEmpleados].rol = [Cop].[dim_roles].rol
LEFT JOIN [Cop].[dim_categorias]
ON [Cop].[ListaProyectos].categoria = [Cop].[dim_categorias].categoria
LEFT JOIN [Cop].[dim_subCategorias]
ON [Cop].[ListaProyectos].subcategoria = [Cop].[dim_subCategorias].subCategoria
left JOIN [Cop].[dim_portfolios]
ON [Cop].[ListaProyectos].[portfolio] = [Cop].[dim_portfolios].portfolio
LEFT JOIN [Cop].[dim_programas]
ON [Cop].[ListaProyectos].program = [Cop].[dim_programas].programa
JOIN [Cop].[dim_torres]
ON [Cop].[timeSheet].torre = [Cop].[dim_torres].torre
imagen
Insert the values that not exist in [Cop].[fact_capacidadOperativa], i don t know if i need to use the where. this insert into is from one stored procedure that i m making
I think something like this
INSERT INTO [Cop].[fact_capacidadOperativa] ([id_empleado],[id_proyecto],[id_rol],[id_categoria],[id_subCategoria],[id_portfolio]
,[id_programa],[horas],[horasPlan],[id_semanaAño],[id_torre])
/*SELECT * FROM [Cop].[timeSheet]*/
select * from (SELECT id_empleado,id_proyecto,id_rol,id_categoria,id_subCategoria,
id_portfolio,id_programa,[Cop].[timeSheet].horas,[Cop].[ListaEmpleados].horaPlan,
[Cop].[timeSheet].nroSemana+[Cop].[timeSheet].año AS id_semanaAño,id_torre FROM [Cop].[timeSheet]
JOIN [Cop].[ListaEmpleados]
ON [Cop].[timeSheet].nombre = [Cop].[ListaEmpleados].recurso
JOIN [Cop].[ListaProyectos]
ON [Cop].[timeSheet].[proyecto] = [Cop].[ListaProyectos].proyecto
JOIN [Cop].[dim_empleados]
ON [Cop].[timeSheet].nombre = [Cop].[dim_empleados].empleado
JOIN [Cop].[dim_proyectos]
ON [Cop].[timeSheet].proyecto = [Cop].[dim_proyectos].proyecto
JOIN [Cop].[dim_roles]
ON [Cop].[ListaEmpleados].rol = [Cop].[dim_roles].rol
JOIN [Cop].[dim_categorias]
ON [Cop].[ListaProyectos].categoria = [Cop].[dim_categorias].categoria
JOIN [Cop].[dim_subCategorias]
ON [Cop].[ListaProyectos].subcategoria = [Cop].[dim_subCategorias].subCategoria
JOIN [Cop].[dim_portfolios]
ON [Cop].[ListaProyectos].[portfolio] = [Cop].[dim_portfolios].portfolio
JOIN [Cop].[dim_programas]
ON [Cop].[ListaProyectos].program = [Cop].[dim_programas].programa
JOIN [Cop].[dim_torres]
ON [Cop].[timeSheet].torre = [Cop].[dim_torres].torre) a
where not exists (select 1 from [Cop].[fact_capacidadOperativa] b where a.id_empleado = b.id_empleado
and a.id_proyecto = b.id_proyecto and a.id_rol = b.id_rol and a.id_categoria = b.id_categoria
and a.id_subCategoria = b.id_subCategoria and a.id_portfolio = b.id_portfolio and a.id_programa = b.id_programa and
a.horas = b.horas and a.horaPlan = b.horasPlan and a.id_torre = b.id_torre and a.id_semanaAño = b.id_semanaAño);
But i don t know it s the best way
As mentioned in the comment, we can create a UNIQUE constraint on all affected columns.
Then we use INSERT IGNORE to only insert valid rows in our target table from the other table(s).
Assume we have two tables, both with column1, column2 and column3 as integers. Now we want to insert all data from one of these tables to the other, but apply a unique constraint on column1 and column2 of the target table.
This will create the unique constraint:
ALTER TABLE yourtable
ADD UNIQUE (column1, column2);
Then this insert commands will only insert valid data in the table which does not violate the unqiue constraint:
INSERT IGNORE INTO yourtable
(SELECT column1, column2, column3 FROM anothertable);
I created a sample fiddle which shows the complete behaviour with and without this constraint and with or without the usage of INSERT IGNORE.
So replicate this idea here: db<>fiddle
Here is the documentation of INSERT IGNORE: documentation
All you need to do is to create the correct unique constraint for your current situation and to make sure your insert command is basically correct. Then only valid rows will be inserted, as shown in the fiddle.

SQL substring Issue ( Where substring(...) = (select....) )

I'm trying to search only the dirname from full path using this queries.
SELECT
`file_name` FROM `tbl_files` where SUBSTR(`file_path`,
LOCATE('/',`file_path`)+1,
(CHAR_LENGTH(`file_path`) - LOCATE('/',REVERSE(`file_path`)) - LOCATE('/',`file_path`))) =
(Select `source_path` from `tbl_transcode_folder` where `trancode_folder_id` = 1 )
But it return me nothing. When i replace (Select source_path from tbl_transcode_folder where trancode_folder_id = 1 ) into it's result mnt/hd/1 like the queries below , It's response want i to but i dont want to do in that way.
SELECT
`file_name` FROM `tbl_files` where SUBSTR(`file_path`,
LOCATE('/',`file_path`)+1,
(CHAR_LENGTH(`file_path`) - LOCATE('/',REVERSE(`file_path`)) - LOCATE('/',`file_path`))) = `mnt/hd/1`
Right now your sub-query returns a random row from the table you need to define a relation between the tbl_transcode_folder table, you need to define a relation between the outer query and the sub-query to make them correlated
SELECT `file_name`
FROM `tbl_files`
where SUBSTR(`file_path`, LOCATE('/',`file_path`)+1
,(CHAR_LENGTH(`file_path`) - LOCATE('/',REVERSE(`file_path`))
- LOCATE('/',`file_path`)))
=(Select `source_path`
from `tbl_transcode_folder`
where `trancode_folder_id` = 1
AND `tbl_files`.`CommonColumn` = `tbl_transcode_folder`.`CommonColumn`)

Operation with values in query inside stored procedure (mysql)

i have a stored procedure in mysql with a couple of queries and i need to perform some operations with that query.
This is some the code from the stored procedure:
BEGIN
SET ##session.collation_connection = ##global.collation_connection;
DROP TEMPORARY TABLE IF EXISTS innerContainers;
CREATE TEMPORARY TABLE `innerContainers` (
`id_container` INT(10) NOT NULL,
`display_name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id_container`)
)
ENGINE = memory;
INSERT INTO innerContainers(id_container, display_name)
(SELECT c1.id_container, c1.display_name
FROM container_presentation cp
LEFT JOIN presentation p USING(id_presentation)
LEFT JOIN container c1 ON p.id_container = c1.id_container
WHERE c1.isDeleted = 0 AND c1.isActive = 1 AND
cp.id_container = in_id_container)
UNION
(SELECT c1.id_container, c1.display_name
FROM container_assembly_item cp
LEFT JOIN presentation p USING(id_presentation)
LEFT JOIN container c1 ON p.id_container = c1.id_container
WHERE c1.isDeleted = 0 AND c1.isActive = 1 AND
cp.id_container = in_id_container);
SELECT mad.id_container,
mat.sign_stock,
ma.id_management_start_point,
ma.id_management_end_point,
mad.quantity
FROM management_activity ma
LEFT JOIN management_activity_type mat ON ma.id_management_activity_type = mat.id_management_activity_type
LEFT JOIN management_activity_detail mad ON ma.id_management_activity = mad.id_management_activity
LEFT JOIN management_stock_point msp ON ma.id_management_end_point = msp.id_management_stock_point
LEFT JOIN management_stock_point msp1 ON ma.id_management_start_point = msp1.id_management_stock_point
WHERE mad.id_container IN (SELECT id_container FROM innerContainers)
ORDER BY mad.id_container ASC;
END
Now, after the last query.. i need to do some operations and return a value for each id_container inside the temporary table depending on the values in the second query.
Something like this:
foreach id_container in the second query i have a resultValue and i need to:
if the sign_stock == 1 and some other conditions then resultValue -= quantity and if sign_stock == 2 and some other conditions then resultValue += quantity.
And the final resultValue after iterating over the id_container lines will be the one i want for that id_container in the temporary table.
I dont know how to do that operation.. can some one help me with that?
Don't create a temporary table unless you need the data after the procedure call. Either way, in order to iterate over the results of a SELECT query, use a CURSOR.
A simple example is provided in the linked manual page.

sql query speed. Time response to long

I have problem with my mysl query. Response time is to long. My query:
SELECT SQL_CALC_FOUND_ROWS
t.id,
l.id_produkt_lista,
z.nr_zam,
k.nazwa_fv,
p.nazwa,
p.opis,
p.data_realizacji,
CONCAT(t.d_graf,'</br>', IF(t.D_d_graf IS NOT NULL,
DATE_FORMAT(t.D_d_graf, "%d-%m-%Y"),"")),
CONCAT(t.d_druk,'</br>', IF(t.D_d_druk IS NOT NULL,
DATE_FORMAT(t.D_d_druk, "%d-%m-%Y"),"")),
CONCAT(t.d_zgrz,'</br>', IF(t.D_d_zgrz IS NOT NULL,
DATE_FORMAT(t.D_d_zgrz, "%d-%m-%Y"),""))
FROM zamowienie_produkt_lista l
JOIN zamowienia_zamowienie z ON (l.id_zamowienie = z.id_zamowienie)
JOIN zamowienia_produkt p ON (l.id_produkt = p.id_produkt)
JOIN zamowienia_prac_tmp t ON (l.id_produkt = t.id_produkt)
JOIN zamowienia_klient k ON (z.id_klient = k.id_klient)
WHERE TRUE
AND id_typ_produkt = '1'
AND z.archiwum = 0
ORDER BY t.id
When I use it in phpmyadmin I have to wait about 10 second
Assuming that id_typ_produkt belongs to table zamowienie_produkt_lista, creating following indexes should help:
CREATE INDEX p_1_idx ON zamowienie_produkt_lista
(id_produkt, id_typ_produkt);
CREATE INDEX z_1_idx ON zamowienia_zamowienie
(id_zamowienie, archiwum);
You should also make sure that indexes on all *_id fields for all other joined tables exist.

Can I use MySQL ifnull with a select statement?

I'm trying the following and cannot find out what is wrong:
IF( IFNULL(
SELECT * FROM vertreter AS ag
WHERE ag.iln = param_loginID
AND ag.verkaeufer = param_sellerILN
),
UPDATE vertreter AS agUp
SET agUp.vertreterkennzeichen
WHERE agUp.iln = param_loginID AND agUp.verkaeufer = param_sellerILN
,
INSERT INTO vertreter AS agIn
( agIn.iln, agIn.verkaeufer, agIn.vertreterkennzeichen, agIn.`status` )
VALUES
( param_loginID, param_sellerILN, param_agentID, 'Angefragt' )
);
Question:
Is this possible at all, to check if a SELECT returns NULL and then do A or B depending?
You need to create unique composite index (iln + verkaeufer).
CREATE UNIQUE INDEX vertreter_iln_verkaeufer ON vertreter (iln, verkaeufer)
http://dev.mysql.com/doc/refman/5.0/en/create-index.html
And then you can do this in one query:
INSERT INTO vertreter
(agIn.iln, agIn.verkaeufer, agIn.vertreterkennzeichen, agIn.`status`)
VALUES (param_loginID, param_sellerILN, param_agentID, 'Angefragt')
ON DUPLICATE KEY UPDATE vertreterkennzeichen = param_agentID
Documentation: http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html