Can I use select statements when inserting into a table? - mysql

I have the following table:
DROP TABLE IF EXISTS `worklist`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `worklist` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
`ENTITY_TYPE_CODE` bigint(20) NOT NULL,
`TYPE_CODE` bigint(20) NOT NUll,
`NAME` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=125 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = #saved_cs_client */;
Insert INTO code (DISPLAY, CODE_GROUP, CODE_KEY, ALIAS) VALUES ('Duplicate Claims Worklist', 'WORKLIST_TYPE', 'DUPLICATE_CLAIM_WORKLIST', 'Duplicate Claims Worklist');
INSERT INTO code (DISPLAY, CODE_GROUP, CODE_KEY, ALIAS) VALUES ('Claim', 'ENTITY', 'CLAIM', 'Claim');
INSERT INTO worklist (ENTITY_TYPE_CODE, TYPE_CODE) VALUES (SELECT ID FROM code WHERE CODE_GROUP = 'ENTITY' and CODE_KEY = 'CLAIM', SELECT ID from code where CODE_GROUP = 'WORKLIST_TYPE' and CODE_KEY = 'DUPLICATE_CLAIM_WORKLIST');
ALTER TABLE workitems ADD WORKITEMS_ID bigint(20) DEFAULT NULL;

Yes you can you need to omit the Values keyword and do something like this
INSERT INTO code (DISPLAY, CODE_GROUP, CODE_KEY, ALIAS)
SELECT DISPLAY, CODE_GROUP, CODE_KEY, ALIAS
FROM SomeTable
Obviously you will need to include a where clause to control the select statement but that's basically it.
EDIT:
It would look something like this (code is untested and has been typed directly into the editor so may have some speeling mistooks.)
DROP TABLE IF EXISTS `worklist`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `worklist` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
`ENTITY_TYPE_CODE` bigint(20) NOT NULL,
`TYPE_CODE` bigint(20) NOT NUll,
`NAME` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=125 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = #saved_cs_client */;
Insert INTO code (DISPLAY, CODE_GROUP, CODE_KEY, ALIAS) VALUES ('Duplicate Claims Worklist', 'WORKLIST_TYPE', 'DUPLICATE_CLAIM_WORKLIST', 'Duplicate Claims Worklist');
INSERT INTO code (DISPLAY, CODE_GROUP, CODE_KEY, ALIAS) VALUES ('Claim', 'ENTITY', 'CLAIM', 'Claim');
INSERT INTO worklist (ENTITY_TYPE_CODE, TYPE_CODE) SELECT A.ID, B.ID FROM (SELECT ID, 1 AS J FROM code WHERE CODE_GROUP = 'ENTITY' and CODE_KEY = 'CLAIM') A LEFT JOIN ( SELECT ID, 1 AS J FROM code WHERE CODE_GROUP = 'WORKLIST_TYPE' and CODE_KEY = 'DUPLICATE_CLAIM_WORKLIST') B ON A.J = B.J;
ALTER TABLE workitems ADD WORKITEMS_ID bigint(20) DEFAULT NULL;

Related

Data Is not getting inserted in Mysql Database in a Node.js Real time notification app

I am trying to build a notification app which can notify changes in msql database using Nodejs and socket.io .
But mydata is not getting inserted in database. Attaching my db.js file and socketDemo.sql. My database name is socket.io
db.js file:-
var addComment = function(user,comment,mysql,pool,callback) {
console.log(user,comment);
var self = this;
pool.getConnection(function(err,connection){
if (err) {
//connection.release();
return callback(true,null);
} else {
var sqlQuery = "INSERT into UserComment (UserName,UserId,Comment) VALUES ((SELECT UserName FROM User WHERE UserName = user),id,comment)";
// var inserts =["UserComment","UserId","UserName",
// "Comment","UserId","User","UserName",
// user,user,comment];
//sqlQuery = mysql.format(sqlQuery,inserts);
connection.query(sqlQuery,function(err,rows){
connection.release();
if (err) {
return callback(true,null);
} else {
callback(false,"comment added");
}
});
}
connection.on('error', function(err) {
return callback(true,null);
});
});
};
module.exports.addComment = addComment;
socketDemo.sql:-
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `socketDemo`
--
-- --------------------------------------------------------
--
-- Table structure for table `User`
--
CREATE TABLE IF NOT EXISTS `User` (
`UserId` int(11) NOT NULL,
`UserName` varchar(25) NOT NULL,
`Password` varchar(25) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `User`
--
INSERT INTO `User` (`UserId`, `UserName`, `Password`) VALUES
(1, 'Harshit', 'Harshit');
-- --------------------------------------------------------
--
-- Table structure for table `UserComment`
--
CREATE TABLE IF NOT EXISTS `UserComment` (
`UserId` int(11) NOT NULL,
`UserName` varchar(11) NOT NULL,
`Comment` text NOT NULL,
`PostId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `UserComment`
--
INSERT INTO `UserComment` (`UserId`, `UserName`, `Comment`, `PostId`) VALUES
(1, 'Harshit', '\n \n \n \n \n ', 0);
-- --------------------------------------------------------
--
-- Table structure for table `UserPost`
--
CREATE TABLE IF NOT EXISTS `UserPost` (
`UserPostId` int(11) NOT NULL,
`UserPostContent` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `UserPost`
--
INSERT INTO `UserPost` (`UserPostId`, `UserPostContent`) VALUES
(1, 'This is test comment.');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `User`
--
ALTER TABLE `User`
ADD PRIMARY KEY (`UserName`),
ADD KEY `UserIdIndex` (`UserId`);
--
-- Indexes for table `UserComment`
--
ALTER TABLE `UserComment`
ADD KEY `UserIdIndexComment` (`UserId`),
ADD KEY `PostIdIndex` (`PostId`);
--
-- Indexes for table `UserPost`
--
ALTER TABLE `UserPost`
ADD PRIMARY KEY (`UserPostId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `User`
--
ALTER TABLE `User`
MODIFY `UserId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `UserPost`
--
ALTER TABLE `UserPost`
MODIFY `UserPostId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
Database schema:-
enter image description here
please help.
My first question is why do you want to use SELECT UserName FROM User WHERE UserName = user - you can simply use the user variable instead the SELECT statement.
What is more, if you are performing such a query and you want to use variables passed to the function, you need to pass them to the .query method:
connection.query("INSERT into UserComment (UserName,UserId,Comment) VALUES (?, ?, ?)", [user, id, comment], function(error, results){
// check error and perform further operations...
});
The [user, id, comment] part is used to replace the ? marks in the SQL query (remember to maintain order of those variables in the array).

how to get ordered result set while using in keyword in mysql

I am trying to run the below query in order to get ordered data from category_child table and accordingly from the category table.
select * from category where id in (select child_id from category_child where category_id=1 order by sequence);
It's like
select * from category where id in (2,3,4);
and
select * from category where id in (3,2,4);
are giving me the same result.
Is there any way I can get the result in the same order.
category and category_child tables are:
-- Table structure for table `category`
--
DROP TABLE IF EXISTS `category`;<br/>
/*!40101 SET #saved_cs_client = ##character_set_client */;<br/>
/*!40101 SET character_set_client = utf8 */;<br/>
CREATE TABLE `category` (<br/>
`id` int(11) NOT NULL AUTO_INCREMENT,<br/>
`name` VARCHAR(50) NOT NULL, <br/>
`description` VARCHAR(250) NOT NULL,<br/>
`image_url` VARCHAR(250),<br/>
`created_on` timestamp NOT NULL DEFAULT '2014-11-06 00:00:00',<br/>
`updated_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, <br/>
PRIMARY KEY (`id`)<br/>
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;<br/>
/*!40101 SET character_set_client = #saved_cs_client */;<br/>
--
-- Table structure for table `category_child`<br/>
--
DROP TABLE IF EXISTS `category_child`;<br/>
/*!40101 SET #saved_cs_client = ##character_set_client */;<br/>
/*!40101 SET character_set_client = utf8 */;<br/>
CREATE TABLE `category_child` (<br/>
`id` int(11) NOT NULL AUTO_INCREMENT,<br/>
`category_id` int(11) NOT NULL,<br/>
`child_id` int(11) NOT NULL,<br/>
`child_type` VARCHAR(100) NOT NULL,<br/>
`sequence` int(4) NOT NULL,<br/>
`created_on` timestamp NOT NULL DEFAULT '2014-11-06 00:00:00',<br/>
`updated_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, <br/>
PRIMARY KEY (`id`)<br/>
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;<br/>
/*!40101 SET character_set_client = #saved_cs_client */;<br/>
following query
select c.*
from category c, category_child cc
where cc.category_id=1 and c.id=cc.child_id
order by cc.sequence;
will work, just a little change in condition in the answer given by Nir-Z and removing join.
Why not doing
Select c.*
from category c
join category_child cc on cc.id=c.category_id
where cc.category_id=1
order by cc.sequence
If you are trying to get them ordered by category_child.sequence, then they will be returned in whatever order the utilized index returns the category results.
So #Nir-Z's answer will get you results sorted by the order of category_child.sequence, but if there were multiple indexes on category you could get differing results.
The only way to enforce consistent results every time would be to provide an order for category as well.
Select c.*
from category c
join category_child cc on cc.category_id=c.id
where cc.category_id=1
order by cc.sequence, c.name
c.name can be any of the fields from category.
You cannot control the result's order with the where clause (at least not deterministically). Instead, you should just add an explicit order by clause:
select * from category where id in (2,3,4) order by id;
select * from category where id in (3,2,4) order by id;

Mysql - The trigger do not update my database

this is my trigger :
--
-- Déclencheurs `reservation`
--
DROP TRIGGER IF EXISTS `UpdateFactureOnInsert`;
DELIMITER //
CREATE TRIGGER `UpdateFactureOnInsert` AFTER INSERT ON `reservation`
FOR EACH ROW BEGIN
DECLARE quota, montant, tarif INT;
DECLARE nombreHeure INT DEFAULT (SELECT COUNT(heure.numero) FROM heure WHERE heure.code = NEW.code);
DECLARE mois INT DEFAULT (SELECT heure.mois FROM heure WHERE heure.code = NEW.code LIMIT 1);
DECLARE annee INT DEFAULT (SELECT heure.annee FROM heure WHERE heure.code = NEW.code LIMIT 1);
DECLARE identifiant INT DEFAULT (SELECT facture.identifiant FROM facture WHERE facture.association = NEW.association
AND facture.mois = mois
AND facture.annee = annee LIMIT 1);
IF (identifiant = null) THEN
SET identifiant = ((SELECT MAX(facture.identifiant) FROM facture) +1);
INSERT INTO facture (facture.association, facture.annee, facture.mois, facture.identifiant, facture.quota, facture.montant)
VALUES (NEW.association, annee, mois, identifiant, 20, 0);
END IF;
SET quota = (SELECT facture.quota FROM facture WHERE facture.identifiant = identifiant
AND facture.association = NEW.association
AND facture.mois = mois
AND facture.annee = annee);
SET montant = (SELECT facture.montant FROM facture WHERE facture.identifiant = identifiant
AND facture.association = NEW.association
AND facture.mois = mois
AND facture.annee = annee);
IF (nombreHeure >= quota) THEN
SET quota = quota - nombreHeure;
ELSE
SET tarif = (SELECT salle.tarif FROM salle WHERE salle.numero = NEW.numero);
SET montant = montant + (nombreHeure - quota) * tarif;
SET quota = 0;
END IF;
UPDATE facture SET facture.quota = quota, facture.montant = montant WHERE facture.association = NEW.association
AND facture.mois = mois
AND facture.annee = annee
AND facture.identifiant = identifiant;
END
//
DELIMITER ;
Those are my:
-- phpMyAdmin SQL Dump
-- version 4.0.4
-- http://www.phpmyadmin.net
--
-- Client: localhost
-- Généré le: Mer 02 Avril 2014 à 17:00
-- Version du serveur: 5.6.12-log
-- Version de PHP: 5.4.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de données: `reserv`
--
CREATE DATABASE IF NOT EXISTS `reserv` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `reserv`;
-- --------------------------------------------------------
--
-- Structure de la table `association`
--
CREATE TABLE IF NOT EXISTS `association` (
`association` int(11) NOT NULL AUTO_INCREMENT,
`libelle` char(32) NOT NULL,
PRIMARY KEY (`association`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
-- --------------------------------------------------------
--
-- Structure de la table `facture`
--
CREATE TABLE IF NOT EXISTS `facture` (
`association` int(11) NOT NULL,
`annee` int(11) NOT NULL,
`mois` int(11) NOT NULL,
`identifiant` int(11) NOT NULL,
`quota` int(11) NOT NULL,
`montant` int(11) NOT NULL,
PRIMARY KEY (`association`,`mois`,`annee`,`identifiant`),
KEY `i_fk_facture_mois` (`mois`,`annee`),
KEY `i_fk_facture_association` (`association`),
KEY `facture_ibfk_1` (`annee`,`mois`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `heure`
--
CREATE TABLE IF NOT EXISTS `heure` (
`numero` int(11) NOT NULL,
`association` int(11) NOT NULL,
`code` int(11) NOT NULL,
`annee` int(11) NOT NULL,
`mois` int(11) NOT NULL,
`jour` int(11) NOT NULL,
`heure` int(11) NOT NULL,
PRIMARY KEY (`numero`,`association`,`code`,`annee`,`mois`,`jour`,`heure`),
KEY `i_fk_heure_mois` (`annee`,`mois`),
KEY `i_fk_heure_reservation` (`numero`,`association`,`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `mois`
--
CREATE TABLE IF NOT EXISTS `mois` (
`mois` int(11) NOT NULL,
`annee` int(11) NOT NULL,
PRIMARY KEY (`annee`,`mois`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `reservation`
--
CREATE TABLE IF NOT EXISTS `reservation` (
`numero` int(11) NOT NULL,
`association` int(11) NOT NULL,
`code` int(11) NOT NULL,
PRIMARY KEY (`numero`,`association`,`code`),
KEY `i_fk_reservation_association` (`association`),
KEY `i_fk_reservation_salle` (`numero`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `salle`
--
CREATE TABLE IF NOT EXISTS `salle` (
`numero` int(11) NOT NULL AUTO_INCREMENT,
`capacite` int(11) NOT NULL,
`tarif` int(11) NOT NULL,
PRIMARY KEY (`numero`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Contraintes pour les tables exportées
--
--
-- Contraintes pour la table `facture`
--
ALTER TABLE `facture`
ADD CONSTRAINT `facture_ibfk_1` FOREIGN KEY (`annee`, `mois`) REFERENCES `mois` (`annee`, `mois`),
ADD CONSTRAINT `facture_ibfk_2` FOREIGN KEY (`association`) REFERENCES `association` (`association`);
--
-- Contraintes pour la table `reservation`
--
ALTER TABLE `reservation`
ADD CONSTRAINT `reservation_ibfk_1` FOREIGN KEY (`association`) REFERENCES `association` (`association`),
ADD CONSTRAINT `reservation_ibfk_2` FOREIGN KEY (`numero`) REFERENCES `salle` (`numero`);
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
Just please tell me how can I fix it, because the trigger doesn't work properly.
One issue I see is that this conditional test:
IF (identifiant = null)
Will never return TRUE. If you want to test whether a variable is set to the NULL value, use the IS NULL operator.
IF (identifiant IS NULL)
I've never used a query as the DEFAULT value for a variable. (That may be valid, I've just never seen it done that way before.)
I'd code it like this:
DECLARE nombreHeure INT;
SELECT COUNT(heure.numero) INTO nombreHeure
FROM heure
WHERE heure.code = NEW.code;
Any place you are assigning the result from a query into a variable, you need to ensure that the query doesn't return more than one row. The query above will return a single row (assuming, that is, it doesn't throw an error), so it's okay.
For a lot of the other queries in your trigger it's not clear (to the casual reader) that these will return only one row.
Another big problem looks like you are local variables have the same name as columns in SQL statements. MySQL isn't going to see that as a reference to a variable, it's going to see it as a reference to a column. (When MySQL encounters a identifier in a SQL statement, it first checks to see if it's a column, only when it can't find a column of that name does it consider that it might be a variable.)
For example:
AND facture.mois = mois
For the reference to mois on the right side, MySQL first looks for a column named that in one of the tables (from any row source in scope), before it looks at it as a variable. In this case, it's going to find mois as a column in facture, so that SQL is basically equivalent to:
AND facture.mois = fracture.mois
which is effectively the same as:
AND facture.mois IS NOT NULL
Basically, you need to ensure that the variable names used in SELECT statements are distinct from all column names in tables referenced by the query.

How to get one column from 2 different tables

I have 2 tables in MySQL registerSMSusers and GroupsSMS. Both the tables have a column named as mobile. From an HTML form I am getting comma separated values like test,alltest,john. These comma separated values will be present in either of the 2 tables. For example test (name column) is present in registerSMSusers and alltest is present in GroupsSMS (GroupName column).
In Java I can split with comma and then check if its present in any of the tables or not.If present then get the mobile. Just wanted to know are there any SQL queries for the same.
This is SQL schema
DROP TABLE IF EXISTS `GroupsSMS`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `GroupsSMS` (
`Name` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`mobile` varchar(20) DEFAULT NULL,
`GroupName` varchar(20) DEFAULT NULL,
`GroupID` int(11) NOT NULL AUTO_INCREMENT,
`dataselected` varchar(50) DEFAULT NULL,
PRIMARY KEY (`GroupID`)
) ENGINE=MyISAM AUTO_INCREMENT=191 DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `registerSmsUsers`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `registerSmsUsers` (
`name` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`mobile` varchar(20) DEFAULT NULL,
`uid` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`uid`),
UNIQUE KEY `mobile` (`mobile`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM AUTO_INCREMENT=83 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = #saved_cs_client */;
And this is the sqlfiddle
I you have split the string in Java
String names[] = csv.split(',');
You can search for the corresponding mobile number in either registerSmsUsers or GroupsSMS with
PreparedStatement stmt = conn.prepareStatment("select u.mobile from registerSmsuser u where u.name = ? union select g.mobile from GroupsSMS g where g.groupname = ?");
stmt.setString(1, names[0]);
stmt.setString(2, names[0]);
ResultSet rs = stmt.executeQuery();
if (rs.first()) {
// do something with the mobile number
}
This will select entries from both the user and the groups table. If you need to know, where the number is from, you can add a fixed string to your select
select u.mobile, 'user' as origin from registerSmsuser u ...
union
select g.mobile, 'groups' as origin from GroupsSMS g ...
MySQL does not have a ready made function for splitting a CSV string. You have to do it manually using SUBSTRING using SUBSTRING_INDEX or using a REGEXP.
See details on a similar problem here
After you have say split the CSV into actual strings which are stored in a table 'CSVTable' {id, strvalue}, you can check like
SELECT G.mobile as mobilenumber
FROM 'GroupsSMS' G LEFT JOIN 'CSVTable' C
on G.GroupName =C.strvalue
WHERE C.strvalue is NOT NULL
UNION
SELECT R.mobile as mobilenumber
FROM 'registerSMSusers' R LEFT JOIN 'CSVTable' C
on R.name=C.strvalue
WHERE C.strvalue is NOT NULL
Note I have not used UNION ALL to get distinct set values
Pseudo code for getting values into temp table
DECLARE #CSVTABLE TABLE ( id int not null, strvalue NVARCHAR(400) NOT NULL)
DECLARE #var int
SET #var=1
DECLARE #STREXP NVARCHAR(MAX)
DECLARE #BUFF NVARHCAR(400)
SET #BUFF=SUBSTRING_INDEX(#STREXP,',',1)
SET #STREXP=REPLACE(#STREXp,#BUFF+',','')
WHILE #BUFF IS NOT NULL DO
INSERT INTO #temp VALUES(#var,#BUFF)
#var=#var+1
#VUFF
END WHILE

MySql join statement returning too many results

I am attempting to join some columns from two tables like follows:
select routes.route_collection, times.times
from routes
inner join times
on routes.bus_id & times.bus_id =1;
Although I am getting 12 results (duplicated by 4) instead of three.
Am I doing something wrong here? I have looked at several sites and they all appear to work using similar syntax.
Edit: It appears to be multiplying the amount of values in one table by another - in this case 4 x 3?
Here is the database schema
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 5.5.32 - MySQL Community Server (GPL)
-- Server OS: Win32
-- HeidiSQL Version: 8.0.0.4459
-- --------------------------------------------------------
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping database structure for mydb
CREATE DATABASE IF NOT EXISTS `mydb` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `mydb`;
-- Dumping structure for table mydb.buses
CREATE TABLE IF NOT EXISTS `buses` (
`bus_id` int(11) NOT NULL,
PRIMARY KEY (`bus_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Dumping data for table mydb.buses: ~5 rows (approximately)
/*!40000 ALTER TABLE `buses` DISABLE KEYS */;
INSERT INTO `buses` (`bus_id`) VALUES
(1),
(2),
(3),
(4),
(5);
/*!40000 ALTER TABLE `buses` ENABLE KEYS */;
-- Dumping structure for table mydb.routes
CREATE TABLE IF NOT EXISTS `routes` (
`route_id` int(11) NOT NULL,
`bus_id` int(11) DEFAULT NULL,
`route_collection` varchar(45) DEFAULT NULL,
`stop_order` int(11) DEFAULT NULL,
PRIMARY KEY (`route_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Dumping data for table mydb.routes: ~4 rows (approximately)
/*!40000 ALTER TABLE `routes` DISABLE KEYS */;
INSERT INTO `routes` (`route_id`, `bus_id`, `route_collection`, `stop_order`) VALUES
(1, 1, 'Douglas,Onchan,Ballasalla,Castletown,Colby', 1),
(2, 1, 'Douglas,Onchan,Ballasalla,Castletown,Colby', 2),
(3, 1, 'Douglas,Onchan,Ballasalla,Castletown,Colby', 3),
(4, 1, 'Douglas,Onchan,Ballasalla,Castletown,Colby', 4);
/*!40000 ALTER TABLE `routes` ENABLE KEYS */;
-- Dumping structure for table mydb.times
CREATE TABLE IF NOT EXISTS `times` (
`time_id` int(11) NOT NULL,
`start_time` int(11) DEFAULT NULL,
`bus_id` int(11) DEFAULT NULL,
`times` varchar(500) DEFAULT NULL,
`period` varchar(45) DEFAULT NULL,
PRIMARY KEY (`time_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Dumping data for table mydb.times: ~3 rows (approximately)
/*!40000 ALTER TABLE `times` DISABLE KEYS */;
INSERT INTO `times` (`time_id`, `start_time`, `bus_id`, `times`, `period`) VALUES
(1, 600, 1, '06:00,07:00,12:00,14:00,23:00', 'MonFri'),
(2, 615, 1, '06:15,07:15,12:15,14:15,23:15', 'MonFri'),
(3, 600, 1, '06:00,07:00,12:00,14:00,23:00', 'Sat');
/*!40000 ALTER TABLE `times` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(#OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(#OLD_FOREIGN_KEY_CHECKS IS NULL, 1, #OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
Please use operator 'AND' instead of '&'.
And as I understand you need something like that (do not know do you need the where clouse):
select routes.route_collection, times.times
from routes
inner join times
on routes.bus_id = times.bus_id
where routes.bus_id = 1;
May be you need aggregated values of times?
something like this:
select routes.route_collection, GROUP_CONCAT(times.times)
from routes
inner join times
on routes.bus_id = times.bus_id
where routes.bus_id = 1
group by routes.route_id;