I do not know if it's possible at all, but I have two tables, userBasic and carPlateConfidence, in carPlateConfidence I would like to insert id of userBasic where emails are matched.
$query .= "INSERT IGNORE INTO userBasic (id_uM, userNameG, userEmailG) values ((SELECT id_uM FROM userMore WHERE userEmailG='$userEmailG'),'$userNameG', '$userEmailG');";
$query .= "INSERT IGNORE INTO carPlateConfidence (emailConfid, id_uB,plateNumber, confidencePlate, plateNumberUn) values ('$userEmailG', (SELECT id_uB FROM userBasic WHERE userEmailG='(SELECT max(emailConfid) FROM carPlateConfidence)'), '$plateNumber','$confidencePlate', '$plateNumberUn');";
So if I have:
userBasic:
id_uM = 555;
userNameG = BlaBla;
userEmailG = blabla#blabla.com
And in this table I would like
carPlateConfidence:
emailConfid = blabla#blabla.com;
id_uB = 555
plateNumber = 1111
confidencePlate = 70
plateNumberUn = 2222
AND if email do not matched:
emailConfid = blabla2#blabla.com;
id_uB = NULL
plateNumber = 1111
confidencePlate = 70
plateNumberUn = 222
P>S> Currently I have tried this, to select id from userBasic:
(SELECT id_uB FROM userBasic WHERE userEmailG='(SELECT max(emailConfid) FROM carPlateConfidence)')
id_uB in carPlateConfidence is set as foreign key;
Tables:
--
-- Table structure for table `carPlateConfidence`
--
DROP TABLE IF EXISTS `carPlateConfidence`;
CREATE TABLE IF NOT EXISTS `carPlateConfidence` (
`id_cof` int(11) NOT NULL AUTO_INCREMENT,
`id_uB` int(11) NOT NULL,
`emailConfid` varchar(50) NOT NULL,
`plateNumber` varchar(10) NOT NULL,
`confidencePlate` varchar(10) DEFAULT NULL,
`plateNumberUn` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id_cof`),
KEY `id_uB` (`id_uB`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
-- --------------------------------------------------------
--
-- Table structure for table `userBasic`
--
DROP TABLE IF EXISTS `userBasic`;
CREATE TABLE IF NOT EXISTS `userBasic` (
`id_uB` int(11) NOT NULL AUTO_INCREMENT,
`id_uM` int(11) NOT NULL,
`userNameG` varchar(50) NOT NULL,
`userEmailG` varchar(50) NOT NULL,
PRIMARY KEY (`id_uB`),
UNIQUE KEY `userEmailG` (`userEmailG`),
KEY `id_uM` (`id_uM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=119 ;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `carPlateConfidence`
--
ALTER TABLE `carPlateConfidence`
ADD CONSTRAINT `carPlateConfidence_ibfk_1` FOREIGN KEY (`id_uB`) REFERENCES `userBasic` (`id_uB`);
--
-- Constraints for table `userBasic`
--
ALTER TABLE `userBasic`
ADD CONSTRAINT `userBasic_ibfk_1` FOREIGN KEY (`id_uM`) REFERENCES `userMore` (`id_uM`);
So you want an update, not an insert :
UPDATE carPlateConfidence t
SET t.id_uB = (SELECT distinct s.id_uM FROM userBasic s
WHERE s.userEmailG = t.emailConfid)
This will work only if there can be only 1 match, if there can be more then one match you should specify which one you want, if it doesn't matter, either use MAX() or limit :
UPDATE carPlateConfidence t
SET t.id_uB = (SELECT max(s.id_uM) FROM userBasic s
WHERE s.userEmailG = t.emailConfid)
Related
I am trying to upload some images to my database with some data, when I do this in localhost it's all work fine. But on the server, only some queries work fine. but others are not working.
This is my database pages table and papertag table
CREATE TABLE `pages`
(
`pageId` int(10) NOT NULL,
`paperId` varchar(255) NOT NULL,
`filePath` varchar(255) NOT NULL,
`fileType` varchar(20) NOT NULL,
`status` enum('0','1') NOT NULL,
`dateAndTime` datetime NOT NULL,
`description` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `pages`
--
ALTER TABLE `pages`
ADD PRIMARY KEY (`pageId`),
ADD KEY `paperId` (`paperId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `pages`
--
ALTER TABLE `pages`
MODIFY `pageId` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=324;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `pages`
--
ALTER TABLE `pages`
ADD CONSTRAINT `pages_ibfk_1` FOREIGN KEY (`paperId`) REFERENCES `papers` (`paperId`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
-----paper tag------
CREATE TABLE `papertag`
(
`tagId` int(11) NOT NULL,
`paperId` varchar(255) NOT NULL,
`tagName` varchar(255) NOT NULL,
`des` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `papertag`
--
ALTER TABLE `papertag`
ADD PRIMARY KEY (`tagId`),
ADD KEY `paperId` (`paperId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `papertag`
--
ALTER TABLE `papertag`
MODIFY `tagId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=460;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `papertag`
--
ALTER TABLE `papertag`
ADD CONSTRAINT `papertag_ibfk_1` FOREIGN KEY (`paperId`) REFERENCES `papers` (`paperId`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
and this is my SQL query code in PHP file
$up22 = mysqli_query($connection, "INSERT INTO papertag(`paperId`, `tagName`) VALUES ('{$paperId}', '{$nme}')");
$up = mysqli_query($connection, "INSERT INTO pages(`paperId`, `filePath`, `fileType`, `status`, `dateAndTime`) VALUES ('{$paperId}', '{$img_dir}', '{$type}',2 , '{$date}' )");
I think you have to insert all columns with not null Constraint. you did not insert des column for example.
you need this code :
$up22 = mysqli_query($connection, "INSERT INTO papertag(`paperId`, `tagName`,`des`) VALUES ('{$paperId}', '{$nme}'),'{$des}'");
I try to show the videos and pictures shared by the members in one page. The query I wrote works fine but is very slow. I don't know why this happened. That's why I need your help. You can also see the conditions I wrote in the following query.
Here is the sqlFiddle
$morequery="";
if($lastpostid) {
$morequery=" AND P.user_post_id<'".$lastpostid."' ";
}
$GetAllPostQuery = mysqli_query($this->db,"SELECT
P.user_post_id,
P.user_id_fk,P.post_type,
P.who_can_see_post,
P.post_image_id,P.post_video_id,
P.post_video_name,
U.user_name, U.user_fullname,U.influencer_status
FROM user_posts P
INNER JOIN users U
ON P.user_id_fk = U.user_id
WHERE
U.user_status='1' AND
U.influencer_status = '1' AND
(P.who_can_see_post IN('everyone','influencer','friends')) AND
(P.post_type IN('image','video')) $morequery
ORDER BY
P.user_post_id
DESC LIMIT " .$this->perpage) or die(mysqli_error($this->db));
//Store the result
while($row=mysqli_fetch_array($GetAllPostQuery)) {
// Store the result into array
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
The Users Table Here:
-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost:8889
-- Generation Time: Sep 10, 2019 at 11:56 AM
-- Server version: 5.7.23
-- PHP Version: 7.2.10
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`user_name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`user_status` enum('0','1','2','3') NOT NULL DEFAULT '0',
`user_fullname` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`influencer_status` enum('0','1') NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
And The User Posts Table Here:
CREATE TABLE `user_posts` (
`user_post_id` int(11) NOT NULL,
`user_id_fk` int(11) DEFAULT NULL,
`post_type` enum('text','image','link’,’video','audio','avatar','cover','gif','location','watermark','which','page','event','blog','group','product','bfaf','inf') NOT NULL DEFAULT 'text',
`post_created_time` int(11) NOT NULL DEFAULT '1524910573',
`who_can_see_post` enum('everyone','onlyme','friends','influencer') NOT NULL DEFAULT 'everyone',
`post_video_id` varchar(255) DEFAULT NULL,
`post_video_name` varchar(255) DEFAULT NULL,
`post_audio_id` varchar(255) DEFAULT NULL,
`post_image_id` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for table `user_posts`
--
ALTER TABLE `user_posts`
ADD PRIMARY KEY (`user_post_id`),
ADD KEY `ex_posts` (`user_id_fk`);
--
-- AUTO_INCREMENT for table `user_posts`
--
ALTER TABLE `user_posts`
MODIFY `user_post_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
--
-- Constraints for table `user_posts`
--
ALTER TABLE `user_posts`
ADD CONSTRAINT `ex_posts` FOREIGN KEY (`user_id_fk`) REFERENCES `users` (`user_id`);
What should I do to make the query work faster? Can you help me.
The fiddle contains too few rows to reproduce the problem but these 2 indexes might help.it really depends on your data distribution.
ALTER TABLE users ADD KEY(user_status,influencer_status);
ALTER TABLE user_posts ADD KEY(who_can_see_post,post_type);
Hi guys I am trying to solve one problem with inserting data to Parent - Child tables. Tables below and also ERR diagram show a structure and PK/FK keys. I am inserting data from webform and PHP is used to capture data and pass it to the database.
Fields in mainTable - F_Name, L_Name and Email are just input textfields,
fields in college tables are checkboxes.
Imagine that one teacher can teach at one, two or three colleges where he checks the checkbox for each college/school where he is teaching. But if he teaches only at one college there is when my problem comes. As all of the "college" tables are linked to "Teacher" with PK/FK.
My question is, is there any way how to store auto generated College ID's if for example teacher is teaching only at one college. At the moment with my PHP it fails and I don't know how to fix it.
I have a example of my PHP under the Schema structure. Just a small note that connection to database works properly.
If this or similar was already asked I do appologize.
Thanks for any tips.
-------------------------------------------------------
-- Schema test
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `test` DEFAULT CHARACTER SET latin1 ;
USE `test` ;
-- -----------------------------------------------------
-- Table `test`.`CollegeA`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeA` (
`CollegeAID` INT(11) NOT NULL AUTO_INCREMENT,
`SchoolA` VARCHAR(45) NOT NULL,
`SchoolB` VARCHAR(45) NOT NULL,
`SchoolC` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeAID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`CollegeB`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeB` (
`CollegeBID` INT(11) NOT NULL AUTO_INCREMENT,
`School1` VARCHAR(45) NOT NULL,
`School2` VARCHAR(45) NOT NULL,
`School3` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeBID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`CollegeC`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeC` (
`CollegeCID` INT(11) NOT NULL AUTO_INCREMENT,
`School11` VARCHAR(45) NOT NULL,
`School22` VARCHAR(45) NOT NULL,
`School33` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeCID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`Teacher`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`Teacher` (
`TeacherId` INT(11) NOT NULL AUTO_INCREMENT,
`F_name` VARCHAR(45) NOT NULL,
`L_name` VARCHAR(45) NOT NULL,
`Email` VARCHAR(45) NOT NULL,
`CollegeAID` INT(11) NOT NULL,
`CollegeBID` INT(11) NOT NULL,
`CollegeCID` INT(11) NOT NULL,
PRIMARY KEY (`MainId`),
INDEX `CollegeAID_idx` (`CollegeAID` ASC),
INDEX `CollegeBID_idx` (`CollegeBID` ASC),
INDEX `CollegeCID_idx` (`CollegeCID` ASC),
CONSTRAINT `CollegeAID`
FOREIGN KEY (`CollegeAID`)
REFERENCES `test`.`CollegeA` (`CollegeAID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeBID`
FOREIGN KEY (`CollegeBID`)
REFERENCES `test`.`CollegeB` (`CollegeBID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeCID`
FOREIGN KEY (`CollegeCID`)
REFERENCES `test`.`CollegeC` (`CollegeCID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
PHP example
if(empty($SchoolA) && empty($SchoolB) && empty($SchoolC)){
$CollegeAId = "";
}
else {
$queryCOLLEGEA = "
INSERT INTO CollegeA (SchoolA, SchoolB, SchoolC)
VALUES('$SchoolA','$SchoolB','$SchoolC')";
$result = mysqli_query($con, $queryCOLLEGEA);
$CollegeAId = mysqli_insert_id($con);
};
if(empty($School1) && empty($School2) && empty($School3)){
$CollegeBId = "";
}
else {
$queryCOLLEGEB = "
INSERT INTO CollegeB (School1, School2, School3)
VALUES('$School1','$School2','$School3')";
$result = mysqli_query($con, $queryCOLLEGEB);
$CollegeBId = mysqli_insert_id($con);
};
if(empty($School11) && empty($School22) && empty($School33)){
$CollegeCId = "";
}
else {
$queryCOLLEGEC = "
INSERT INTO CollegeB (School11, School22, School33)
VALUES('$School11','$School22','$School33')";
$result = mysqli_query($con, $queryCOLLEGEC);
$CollegeCId = mysqli_insert_id($con);
};
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', '$CollegeAId', '$CollegeBId', '$CollegeCId')";
$result = mysqli_query($con, $queryMain);
You are using NOT NULL column as foreign key. In this case you cannot leave it empty, you must set here correct key from referenced table. You can change table definition to
CREATE TABLE IF NOT EXISTS `test`.`Teacher` (
`TeacherId` INT(11) NOT NULL AUTO_INCREMENT,
`F_name` VARCHAR(45) NOT NULL,
`L_name` VARCHAR(45) NOT NULL,
`Email` VARCHAR(45) NOT NULL,
`CollegeAID` INT(11),
`CollegeBID` INT(11),
`CollegeCID` INT(11),
PRIMARY KEY (`MainId`),
INDEX `CollegeAID_idx` (`CollegeAID` ASC),
INDEX `CollegeBID_idx` (`CollegeBID` ASC),
INDEX `CollegeCID_idx` (`CollegeCID` ASC),
CONSTRAINT `CollegeAID`
FOREIGN KEY (`CollegeAID`)
REFERENCES `test`.`CollegeA` (`CollegeAID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeBID`
FOREIGN KEY (`CollegeBID`)
REFERENCES `test`.`CollegeB` (`CollegeBID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeCID`
FOREIGN KEY (`CollegeCID`)
REFERENCES `test`.`CollegeC` (`CollegeCID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
In this table you can insert NULL values into CollegeAID, CollegeBID and CollegeCID. So, if teacher works in college, it will have value in appropriate CollegeID. If no - CollegeID will be NULL.
Also you will ned to change your code. Change you code like this
if(empty($SchoolA) && empty($SchoolB) && empty($SchoolC)){
$CollegeAId = null;
}
for all three colleges. You need null, not empty string.
And another change is needed here
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', '$CollegeAId', '$CollegeBId', '$CollegeCId')";
Variable $CollegeAId now contains proper NULL value. But this query will be produced into
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('F_Name', 'L_Name', 'Email', '', 'CollegeBId', 'CollegeCId')
See it? Still empty string instead of NULL! You need to change query string. It must looks like
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('F_Name', 'L_Name', 'Email', NULL, 'CollegeBId', 'CollegeCId')
For example, you can do it this way for college A:
$CollegeAId = isset($CollegeAId) ? "'$CollegeAId'" : 'NULL';
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', $CollegeAId, '$CollegeBId', '$CollegeCId')";
I'm trying to get this MySQL code to work, but it's saying 0 rows affected.
UPDATE assessments, assessment_types
SET assessments.assessment_type_id = assessment_types.id
WHERE (assessment_types.description = "Skills Assessment" AND assessments.id = 2);
Basically I have assessment_types with id and description column, and I just have the id in the assessments.assessment_type_id
I need to update the id.
I searched and couldn't find quite what I need for this.
Thanks!
Table Data:
assessment_types
id description
1 Knowledge Assessment
2 Skill Assessment
3 Personal Information
4 Natural Skills
Table Structure:
--
-- Table structure for table `assessments`
--
CREATE TABLE IF NOT EXISTS `assessments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_bin NOT NULL,
`acronym` varchar(255) COLLATE utf8_bin NOT NULL,
`assessment_type_id` int(11) NOT NULL,
`language_id` int(11) NOT NULL,
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_updated` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `assessment_type_id` (`assessment_type_id`),
KEY `language_id` (`language_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2385 ;
--
-- Table structure for table `assessment_types`
--
CREATE TABLE IF NOT EXISTS `assessment_types` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(255) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=7 ;
You can try doing an explicit join of the two tables in your UPDATE statement:
UPDATE assessments a
INNER JOIN assessment_types at
ON a.assessment_type_id = at.id
SET a.assessment_type_id = at.id
WHERE (at.description = "Skills Assessment" AND a.id = 2);
These are the two table structure of my db
-- Table structure for table `gf_actor`
CREATE TABLE IF NOT EXISTS `gf_actor` (
`actor_id` bigint(20) NOT NULL auto_increment,
`actor_name` varchar(100) default NULL,
PRIMARY KEY (`actor_id`),
UNIQUE KEY `actor_name` (`actor_name`)
) ENGINE=MyISAM;
-- Table structure for table `gf_film_actor`
CREATE TABLE IF NOT EXISTS `gf_film_actor` (
`film_id` int(20) NOT NULL,
`actor_id` int(20) NOT NULL,
KEY `film_id` (`film_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
So i need a query which fetches five related actors name and id from gf_actor table who is having acted in movies which was performed by the actor_id lets say actor_id=1 and movies must be different that means five related actors must be acted in different movies with the actor_id=1
Try this
select ga.actor_id, actor_name from gf_actor ga inner join gf_film_actor gf on ga.actor_id = gf.actor_id where gf.film_id in (select gf1.film_id from gf_film_actor gf1 where gf1.actor_id=1) AND gf.actor_id != 1 LIMIT 5
You have wrong table structure. It should be like:
CREATE TABLE IF NOT EXISTS `gf_actor` (
`actor_id` bigint(20) NOT NULL auto_increment,
`actor_name` varchar(100) default NULL,
PRIMARY KEY (`actor_id`),
UNIQUE KEY `actor_name` (`actor_name`)
) ENGINE=MyISAM;
CREATE TABLE IF NOT EXISTS `gf_film` (
`film_id` int(20) NOT NULL,
`performed_by_actor_id` bigint(20) NOT NULL,
KEY `film_id` (`film_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `gf_film_actor` (
`film_id` int(20) NOT NULL,
`actor_id` bigint(20) NOT NULL,
KEY `film_actor_id` (`film_id`, `actor_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
And now you can create your query like this:
SELECT a.*
FROM `gf_film` AS f
LEFT JOIN `gf_film_actor` AS fa ON f.`film_id` = fa.`film_id`
LEFT JOIN `gf_actor` AS a ON fa.`actor_id` = a.`actor_id`
WHERE f.`performed_by_actor_id` = 1
LIMIT 0, 5;