JOIN table, receiving NULL answers - mysql

I have a problem on a script I'm writing and I don't know where I'm wrong.
I have multiple tables that are being filled from some txt files.
Afterwards I ALTER a table adding a column that must be filled from the result of a JOIN with two other tables.
More specific in my current db I'm trying to insert in table 2 the id of the doctors that are currently in table 1 and 2. One table contains the id and name, and the 2nd the name.
Running this script:
insert into Intermediara.id_provizoriumed
select Medici.id_medic is not null
FROM Medici
LEFT Join Intermediara
ON Medici.Nume COLLATE utf8_romanian_ci =Intermediara.NumeMedic;
or
Insert into Intermediara(id_provizoriumed)
Select DISTINCT Pacienti.Id_pacient
FROM Pacienti
left JOIN Intermediara
ON Pacienti.NumePacient COLLATE utf8_romanian_ci = Intermediara.NumePacient;
will result me in NULL answers;
Any ideas, please? :<
*More info on the project intself:
I'm using a procedure to create the tables:
delimiter $$
CREATE PROCEDURE init()
begin
CREATE TABLE Medici (
Nume VARCHAR(50),
Prenume VARCHAR(225),
Statut ENUM ('primar', 'specialist'),
Specialitate VARCHAR(20),
UNIQUE (Nume, Prenume)) DEFAULT CHARACTER SET utf8 COLLATE utf8_romanian_ci;
ALTER TABLE Medici ADD COLUMN Id_medic int AUTO_INCREMENT PRIMARY KEY;
ALTER TABLE Medici ADD COLUMN Tip ENUM ('primar', 'specialist') AFTER Prenume;
ALTER TABLE Medici DROP COLUMN Statut;
DESCRIBE Medici;
CREATE TABLE Pacienti (
Id_pacient int AUTO_INCREMENT NOT NULL PRIMARY KEY,
NumePacient VARCHAR(50),
PrenumePacient VARCHAR(100),
UNIQUE (NumePacient, PrenumePacient))DEFAULT CHARACTER SET utf8 COLLATE utf8_romanian_ci;
DESCRIBE Pacienti;
CREATE TABLE Cabinete (
Id_cabinet int AUTO_INCREMENT NOT NULL PRIMARY KEY,
Denumire VARCHAR(50),
UNIQUE (Denumire));
DESCRIBE Cabinete;
CREATE TABLE Vizite (
IntervalData DATETIME,
id_m int,
id_p int,
id_Cab int,
FOREIGN KEY (id_m) REFERENCES Medici(Id_medic),
FOREIGN KEY (id_p) REFERENCES Pacienti(Id_pacient),
FOREIGN KEY (id_Cab) REFERENCES Cabinete(Id_cabinet)
);
DESCRIBE Vizite;
CREATE TABLE Intermediara (
DataVizita VARCHAR(50),
OraIntrare TIME,
NumePacient VARCHAR(50),
PrenumePacient VARCHAR(50),
NumeMedic VARCHAR(50),
PrenumeMedic VARCHAR(50),
Cabinet VARCHAR(50)) DEFAULT CHARACTER SET utf8 COLLATE utf8_romanian_ci;
DESCRIBE Intermediara;
end$$
delimiter ;
Afterwards I'm loading the data in the tables Medici and Intermediara;
Then adding the info I need in:
INSERT IGNORE INTO Pacienti(NumePacient, PrenumePacient) SELECT NumePacient, PrenumePacient FROM Intermediara;
INSERT IGNORE INTO Cabinete(Denumire) SELECT Cabinet FROM intermediara;
And then what I'm trying to do is to add in Intermediara after adding:
ALTER TABLE Intermediara add column id_provizoriumed int collate utf8_romanian_ci;
ALTER TABLE Intermediara add column id_provizoriupac int collate utf8_romanian_ci;
ALTER TABLE Intermediara add column id_provizoriucab int collate utf8_romanian_ci;
to add the id from Medici (id_medic) in Intermediara by doing a JOIN having Medici.Nume and Intermediara.NumeMedic in the tables, the id must be distinct;

Related

alter table 'xyztaable' auto_increment=201; not working in mysql. why?

Dear MySQL pros out there: I wonder what I am doing wrong. My code is like:
use testdb;
drop table testtable;
create table testtable (
ID int NOT NULL,
lastn VARCHAR(20) NOT NULL,
firstn varchar(20));
Select * from testtable;
alter table testtable auto_increment = 7001;
insert into testtable (lastn,firstn) values('kim','jeff');
Select * from testtable;
insert into testtable (lastn,firstn) values('Lee','jim');
Select * from testtable;
The table generated as follows: (no effect from "alter" statement)
# ID, lastn, firstn
'0', 'kim', 'jeff'
'0', 'Lee', 'jim'
Either change your CREATE TABLE command to set the ID field to auto increment and initialise it like this:
create table testtable (
ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
lastn VARCHAR(20) NOT NULL,
firstn varchar(20))
AUTO_INCREMENT = 7001;
or alter the table afterwards:
create table testtable (
ID int NOT NULL,
lastn VARCHAR(20) NOT NULL,
firstn varchar(20));
ALTER TABLE testtable MODIFY COLUMN ID INT PRIMARY KEY AUTO_INCREMENT;
ALTER TABLE testtable AUTO_INCREMENT = 7001;
ID needs to be both AUTO_INCREMENT and the PRIMARY KEY. (Those are "sufficient" but not completely "necessary".)

Reserve/Assign a new row in another table with each row added in one

I'll like to find out if it's possible to do the following:
after insertion of data into table a, a row will be created automatically in table b and the Note_Id (its primary key) will be stored in one of the attributes (which is a foreign key that references to the primary key in table b) in table a.
CREATE TABLE table_a ( D_Id int(5) NOT NULL AUTO_INCREMENT,
User_Id int(8) not null,
Note_Id int(5) not null, -- this is the foreign key that points to table b
PRIMARY KEY (D_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE table_b ( Note_Id int(5) NOT NULL AUTO_INCREMENT,
Note_Description varchar(50) null,
PRIMARY KEY (Note_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Thanks!
delimiter $$
CREATE TRIGGER ins_Document
AFTER INSERT ON TABLE_A FOR EACH ROW
BEGIN
set #notenum=(Select max(Note_Id) from TABLE_B);
if(#notenum=0) then begin new.Note_Id=1;
end;
else
new.Note_Id=#notenum+1;
end if;
INSERT INTO TABLE_B (Note_Id) VALUES (NEW.Note_Id);
END$$
delimiter ;
Have a look into triggers: Create Trigger
Here you can react on events like inserts into a table and define respective actions for that.

How to Add integer column to an String column in MySQl 5.0

I Want to add an Integer Column to a String that's because i need to generate a varchar variable with a numeric part that automatically increments. For example, P000001,P000002...
In order to do that what i am doing while creation of table i have taken an int field ID which auto_increments and i am Concatenating P with 00000 and the ID value
The Table i have created is :
CREATE TABLE tblAcceptTest(
ID int AUTO_INCREMENT NOT NULL primary key,
PatientID as CONCAT('P' , CONCAT('000000',CAST(ID as char)))
);
It Shows me the error from as keyword.
Please help
MySQL's documentation (http://dev.mysql.com/doc/refman/5.1/en/create-table.html) says, "the default value must be a constant; it cannot be a function or an expression." Why don't you just get the PatientID value afterward as part of the SELECT:
SELECT CONCAT('P', LPAD(ID, 6, 0)) AS PatientID FROM tblAcceptTest;
It looks like you want six digits after the "P", so try this for your expression:
CONCAT('P', LPAD(ID, 6, '0'))
Mysql has little support for computed columns.
Patient ID from your specification could be a char(7)
CREATE TABLE tblAcceptTest(
ID int AUTO_INCREMENT NOT NULL primary key,
PatientID char(7)
);
Then create some triggers. Note that the following insert trigger will cause issues with high concurrency servers.
DELIMITER |
CREATE TRIGGER tblAcceptTest_insert BEFORE INSERT ON tblAcceptTest
FOR EACH ROW BEGIN
DECLARE next_id INT;
SET next_id = (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='tblAcceptTest');
SET NEW.PatientID = CONCAT('P' , RIGHT(CONCAT('000000',next_id),6)) ;
END;
|
CREATE TRIGGER tblAcceptTest_update BEFORE UPDATE ON tblAcceptTest
FOR EACH ROW BEGIN
SET NEW.PatientID = CONCAT('P' , RIGHT(CONCAT('000000',NEW.ID),6)) ;
END;
|
DELIMITER ;
You use relationships and views to achieve the same result.
CREATE TABLE `patient` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`patient` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `accepted_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`patient_id` int(11) NOT NULL,
`accepted` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `patient_id` (`patient_id`),
CONSTRAINT `accepted_test_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create or replace view accepted_test_veiw as
select CONCAT('P' , RIGHT(CONCAT('000000',patient_id),6)) patient_key
, accepted
, id accepted_test_id
, patient_id
from accepted_test ;
select * from `accepted_test_veiw`

Fill MySQL records one-to-many related tables in one action

I have two MySQL tables with an one-to-many relationship between them. For example:
CREATE TABLE test1 (
pk1 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue1 INTEGER
);
CREATE TABLE test2 (
pk2 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue2 VARCHAR(50),
fk2 INTEGER NOT NULL,
FOREIGN KEY (fk2) REFERENCES test1 (pk1)
);
If I want to insert records in both tables I can first insert a record in the PK table (e.g. INSERT INTO test1 SET testvalue1=100), determine the PK value (e.g. SELECT MAX(pk1) AS LastId FROM test1 or use LAST_INSERT_ID())
and finally use that value to fill the FK column in the second table.
But is it possible to achieve this all in 1 command/query/action? So let's MySQL fill in the PK- and FK-values using the AUTO INCREMENTs?
You should use two INSERT commands; or try to use an INSERT-trigger.
EDIT:
--An example with trigger:
CREATE TABLE dept(
id INT(11) NOT NULL AUTO_INCREMENT,
dept_name VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
CREATE TABLE emp(
id INT(11) NOT NULL AUTO_INCREMENT,
emp_name VARCHAR(255) DEFAULT NULL,
dept_id INT(11) DEFAULT NULL,
PRIMARY KEY (id),
CONSTRAINT FK_emp_dept_id FOREIGN KEY (dept_id)
REFERENCES dept (id) ON DELETE RESTRICT ON UPDATE RESTRICT
)
ENGINE = INNODB;
DELIMITER $$
CREATE TRIGGER trigger1
AFTER INSERT
ON dept
FOR EACH ROW
BEGIN
INSERT INTO emp VALUES (NULL, 'Someone', NEW.id);
END
$$
DELIMITER ;
-- Try to add new department.
INSERT INTO dept VALUES(NULL, 'Sales');
-- Is there new default employee?
SELECT * FROM emp;
+----+----------+---------+
| id | emp_name | dept_id |
+----+----------+---------+
| 1 | Someone | 1 |
+----+----------+---------+

Mysql - second auto_increment col with diff behaviour

I have a proposals table like this
- ID (auto_increment)
- proposal_id
- client_id
There a way in sql that the proposal_id increments just for each client_id
example:
ID proposal_id client_id
1 1 1
2 1 2
3 2 1
4 3 1
5 2 2
6 3 2
i know i can get the last poposal_id and +1 and i add the new entry... but i dont want to do a sql instruction just to get this value... instead i want to use in a sql!
Tkz
Roberto
As I understand you wish to have proposal_id as a sequence in a continuos manner per client_id. Either you should normalize the table to split into per-client-table [tricky and not advisable] to do this or write a SELECT
I think this is what you want if using innodb (recommended) although you can simplify this with myisam
delimiter ;
drop table if exists customer;
create table customer(
cust_id int unsigned not null auto_increment primary key,
name varchar(255) unique not null,
next_proposal_id smallint unsigned not null default 0
)engine = innodb;
insert into customer (name) values ('c1'),('c2'),('c3');
drop table if exists proposal;
create table proposal(
cust_id int unsigned not null,
proposal_id smallint unsigned not null,
proposal_date datetime not null,
primary key (cust_id, proposal_id) -- composite clustered primary key
)engine=innodb;
delimiter #
create trigger proposal_before_ins_trig before insert on proposal for each row
begin
declare new_proposal_id smallint unsigned default 0;
select next_proposal_id+1 into new_proposal_id from customer
where cust_id = new.cust_id;
update customer set next_proposal_id = new_proposal_id where cust_id = new.cust_id;
set new.proposal_id = new_proposal_id;
set new.proposal_date = now();
end#
delimiter ;
insert into proposal (cust_id) values (1),(2),(1),(3),(2),(1),(1),(2);
select * from proposal;
select * from customer;
hope it helps :)
i've added the myisam version below for good measure:
drop table if exists customer;
create table customer(
cust_id int unsigned not null auto_increment primary key,
name varchar(255) unique not null
)engine = myisam;
insert into customer (name) values ('c1'),('c2'),('c3');
drop table if exists proposal;
create table proposal(
cust_id int unsigned not null,
proposal_id smallint unsigned not null auto_increment,
proposal_date datetime not null,
primary key (cust_id, proposal_id) -- composite non clustered primary key
)engine=myisam;
insert into proposal (cust_id,proposal_date) values
(1,now()),(2,now()),(1,now()),(3,now()),(2,now()),(1,now()),(1,now()),(2,now());
select * from customer;
select * from proposal order by cust_id;
I think that you could design a complicated enough query to take care of this without any non-sql code, but that's not in the spirit of what you're asking. There is not a way to create the type of field-specific increment that you're asking for as a specification of the table itself.