I have big data and The first query is too big.
So I make a procedure from the first query. I need procedure (data) join another table join.
DELIMITER $$
CREATE PROCEDURE sales_pro()
BEGIN
SELECT * FROM sales;
END;
select * from sales
where sales.rep_id= sales_pro.rep_id
CREATE TABLE IF NOT EXISTS `reps` (
`rep_id` int(11) NOT NULL,
`rep_name` TEXT(50) NOT NULL
);
INSERT INTO `reps` (`rep_id`, `rep_name`) VALUES
(1, 'John'),
(2, 'Sally'),
(3, 'Joe'),
(4, 'Bob');
CREATE TABLE IF NOT EXISTS `sales` (
`prod_id` int(11) NOT NULL,
`rep_id` int(11) NOT NULL,
`sale_date` DATE NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`prod_id`,`rep_id`,`sale_date`),
KEY `rep_id` (`rep_id`)
);
INSERT INTO `sales` (`prod_id`, `rep_id`, `sale_date`, `quantity`) VALUES
(1, 1, '2013-05-16', 20);
You can't join with a procedure, but you can do it with a view, which can be treated like a table (although there are some restrictions).
CREATE VIEW sales_view AS
SELECT * FROM sales;
SELECT *
FROM sales AS s
JOIN sales_view AS sv ON s.rep_id = sv.rep_id
You can't pass parameters to a view, but you can access columns in the WHERE clause.
SELECT *
FROM sales AS s
JOIN sales_view AS sv ON s.rep_id = sv.rep_id
WHERE sv.quantity > 10;
Related
I want to use a function inside a select query.
This is my test database.
When I use a select, get a result, but the function is running twice... why? I want to insert one row in this case.
Help, please!
create database db1_test;
use db1_test;
create table t1(
id int(11) primary key auto_increment,
t1col1 varchar(20) not null,
t1col2 int(1) not null
);
create table t2(
id int(11) primary key auto_increment,
t2col1 int(11) not null,
t2col2 datetime
);
insert into t1 (t1col1, t1col2) values ('row1', 1);
insert into t1 (t1col1, t1col2) values ('row2', 0);
insert into t1 (t1col1, t1col2) values ('row4', 1);
drop function if exists func1;
DELIMITER $$
CREATE FUNCTION func1(id int) RETURNS datetime
BEGIN
insert into t2 (`t2col1`, `t2col2`) values (id, now());
RETURN now();
END $$
DELIMITER ;
TEST :
SELECT id, t1col2, func1(id) FROM `t1` WHERE 1 and `t1`.`t1col1`='row1';
SELECT id, t1col2, func1(id) FROM `t1` WHERE 1 and `t1`.`t1col1`='row2';
SELECT id, t1col2, func1(id) FROM `t1` WHERE 1 and `t1`.`t1col1`='row4';
Functions are generally used to store reuseable code which returns a scalar value from a calculation or transformation. I think you could
insert into t2(t2col1,t2col2)
SELECT id, now()
FROM `t1`
WHERE `t1`.`t1col1`='row1';
I have a MYSQL table called tbl_product
Another table called tb_opciones_productos
And a third table called tb_opciones
I need to show every item from tbl_product as follows:
How can I get one item from tbl_product and the needed rows from tb_opciones_producto to get the needed result?
EDIT:
This is my current query proposal:
SELECT tbl_product.*,
GROUP_CONCAT( (SELECT CONCAT(tb_opciones.nombre, "(+$", tb_opciones.precio, ")")
FROM tb_opciones WHERE tb_opciones.id_opcion = tb_opciones_productos.id_opcion) SEPARATOR "<br>" ) as options FROM tbl_product
INNER JOIN tb_opciones_productos ON tbl_product.id = tb_opciones_productos.producto
I've create a little sqlfiddle to test : http://sqlfiddle.com/#!9/fc3316/16
You can GROUP_CONCAT a sub-query. It may not be optimized, but it do the job.
PS: next time, can you provide a sample structure ?
Structure :
CREATE TABLE IF NOT EXISTS `products` (
`id` int(6) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `products` (`id`, `name`) VALUES
(1, 'Product Lorem'),
(2, 'Product Ipsum');
CREATE TABLE IF NOT EXISTS `products_options` (
`id_product` int(6) unsigned NOT NULL,
`id_option` int(6) unsigned NOT NULL,
PRIMARY KEY (`id_product`, `id_option`)
) DEFAULT CHARSET=utf8;
INSERT INTO `products_options` (`id_product`, `id_option`) VALUES
(1, 1),
(1, 2),
(1, 3),
(2, 3);
CREATE TABLE IF NOT EXISTS `options` (
`id` int(6) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`value` double NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `options` (`id`, `name`, `value`) VALUES
(1, 'Option A', 42),
(2, 'Option B', 6),
(3, 'Option C', 12);
Request :
SELECT products.*,
GROUP_CONCAT(options.name, " (+$", options.value, ")" SEPARATOR "<br>")
FROM products
INNER JOIN products_options
ON products.id = products_options.id_product
INNER JOIN options
ON products_options.id_option = options.id
GROUP BY products.id
With your Structure, I think this one will work :
SELECT tbl_product.*,
GROUP_CONCAT(tb_opciones.nombre, " (+$", tb_opciones.precio, ")" SEPARATOR "<br>")
FROM tbl_product
INNER JOIN tb_opciones_productos
ON tbl_product.id = tb_opciones_productos.producto
INNER JOIN tb_opciones
ON tb_opciones_productos.opcion = tb_opciones.id
GROUP BY tbl_product.id
I'm trying to retrieve values by joining two tables (the customer and enquiry table),then i'm trying to store the retrieved values into another table that would come in handy for reasons irrelevant here.And then i'm finally deleting the retrieved values from the enquiry table. When i'm trying to execute the stored procedure i'm getting the following error shown in the screenshot below.
how do i resolve this error?
Stored Procedure:-
CREATE PROCEDURE `backup_eq`(
IN `eq` VARCHAR(15), IN `mail` VARCHAR(30), IN `dates` DATE, IN `cmp` VARCHAR(10), IN `rea` VARCHAR(50))
NOT DETERMINISTIC MODIFIES SQL DATA SQL SECURITY DEFINER
BEGIN
SELECT eqno into #eno,Date1 into #d,cmpname into #c,subject into #s,cid into #cd
FROM `enquiry` NATURAL JOIN `customer`
WHERE eqno=eq and email=mail and cmpname=cmp and Date=dates;
INSERT INTO `enquiryBin`(`Eqno`, `Date1`, `Cmpname`, `Subject`, `CID`, `Reason`)
VALUES (#eno,#d,#c,#s,#cd,rea);
DELETE FROM `enquiry`
WHERE eqno=eq and cid=#cd and cmpname=cmp and Date1=dates;
END
The create table statements of the two tables are given below
CREATE TABLE `customer` (
`CID` int(15) NOT NULL,
`Address` varchar(100) NOT NULL,
`Name` varchar(20) NOT NULL,
`email` varchar(30) NOT NULL,
`phone` bigint(20) NOT NULL
)
ALTER TABLE `customer`
ADD PRIMARY KEY (`CID`);
CREATE TABLE `enquiry` (
`Eqno` varchar(15) NOT NULL,
`Date1` date NOT NULL,
`Cmpname` varchar(10) NOT NULL,
`Subject` varchar(100) NOT NULL,
`CID` int(15) NOT NULL
)
ALTER TABLE `enquiry`
ADD PRIMARY KEY (`Eqno`,`Cmpname`,`CID`,`Date1`)
SELECT eqno into #eno,Date1 into #d,cmpname into #c,subject into #s,cid into #cd
Should be
SELECT eqno, Date1, cmpname, subject, cid INTO #eno, #d, #c, #s, #cd
That is, name all columns in the select-list separately from the INTO clause.
Refer to syntax documentation: https://dev.mysql.com/doc/refman/5.7/en/select-into.html
There's no need for all those variables, just use an INSERT INTO ... SELECT query, and a JOIN in the DELETE query.
INSERT INTO enquiryBin (`Eqno`, `Date1`, `Cmpname`, `Subject`, `CID`, `Reason`)
SELECT eqno, Date1, cmpname, subject, cid, rea
FROM FROM `enquiry` NATURAL JOIN `customer`
WHERE eqno=eq and email=mail and cmpname=cmp and Date1 = dates;
DELETE e FROM enquiry AS e
NATURAL JOIN customer
WHERE eqno = eq AND email = mail AND cmpname = cmp AND Date1 = dates
_
Hello everyone!
I have table
CREATE TABLE `labels` (
`id` INT NULL AUTO_INCREMENT DEFAULT NULL,
`name` VARCHAR(250) NULL DEFAULT NULL,
`score` INT NULL DEFAULT NULL,
`before_score` INT NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
And I Have This Table
CREATE TABLE `scores` (
`id` INT NULL AUTO_INCREMENT DEFAULT NULL,
`name_id` INT NULL DEFAULT NULL,
`score` INT NULL DEFAULT NULL,
`date` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`)
);
And i want have result where labels.score - have value last scores.score sorted by scores.date and labels.before_score where have value penultimate scores.score sorted by scores.date. Can I do This Only on Mysql slq and how?
Thanks.
ADD
For example i have this data on first table:
INSERT INTO `labels` (id, name, score, before_score) VALUES (1, 'John', 200, 123);
INSERT INTO `labels` (id, name, score, before_score) VALUES (2, 'Eddie', 2000, 2000);
INSERT INTO `labels` (id, name, score, before_score) VALUES (3, 'Bob', 400, 3101);
And second table
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('1','1','12','2013-07-10');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('2','2','2000','2013-05-04');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('3','3','654','2012-09-12');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('4','1','123','2013-12-17');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('5','1','200','2014-04-25');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','3','3101','2013-12-02');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','2','2000','2015-12-02');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','3','400','2013-12-02');
If I understand correctly, you need the last two scores for each name_id.
I would tackle this with temporary tables:
Step 1. Last score:
create temporary table temp_score1
select name_id, max(`date`) as lastDate
from scores
group by name_id;
-- Add the appropriate indexes
alter table temp_score1
add unique index idx_name_id(name_id),
add index idx_lastDate(lastDate);
Step 2. Penultimate score. The idea is exactly the same, but using temp_score1 to filter the data:
create temporary table temp_score2
select s.name_id, max(`date`) as penultimateDate
from scores as s
inner join temp_score1 as t on s.nameId = t.nameId
where s.`date` < t.lastDate
group by name_id;
-- Add the appropriate indexes
alter table temp_score2
add unique index idx_name_id(name_id),
add index idx_penultimateDate(penultimateDate);
Step 3. Put it all together.
select
l.id, l.name,
s1.lastScore, s2.penultimateScore
from
`labels` as l
left join temp_score1 as s1 on l.id = s1.name_id
left join temp_score2 as s2 on l.id = s2.name_id
You can put this three steps inside a stored procedure.
Hope this helps you.
Sorry for long POST:
Is it possible that I can call a Stored Procedures from another
Stored procedure in MySQL.
For example:
I have two tables (test and testcomp):
With the structures below:
-- Table structure for table test
CREATE TABLE IF NOT EXISTS `test` (
`t_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`t_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
and
-- Table structure for table testcomp
CREATE TABLE IF NOT EXISTS `testcomp` (
`c_id` int(11) NOT NULL AUTO_INCREMENT,
`t_id` int(4) NOT NULL,
`place` varchar(255) NOT NULL,
PRIMARY KEY (`c_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
Now I populated test table with:
INSERT INTO `test` (`t_id`, `name`) VALUES
(1, 'foo'),
(2, 'bar'),
(3, 'ma');
and table testcomp with:
INSERT INTO `testcomp` (`c_id`, `t_id`, `place`) VALUES
(1, 1, 'gugs'),
(2, 2, 'nyanga'),
(3, 1, 'gugs'),
(4, 3, 'skom');
Now if I have 2 Procedures:
First QryTestComp:
SELECT t_id, place FROM TestComp
The one above works as the just querying normal table:
But the Second One QryTestPlac, which calls the above procedure:
SELECT * FROM Test INNER JOIN QryTestComp ON Test.t_id = QryTestComp.t_id
Comes with a error:
It says Error: 1146 (42S01): Table 'mydb.qrytestcomp' doesn't exist.
It not a table but a procedure.
Pointer, please.
Regards,
--Jongi
you can't join onto a stored procedure, perhaps using views might be more suitable ?