I have a scenario where i have one main table. Main table has 2 extra columns one is for table name (child table name) and other is for table id (child table id). when we enter the value in main table we also tell enter value in child table and then we enter the name of the table in main table name field and child id in the child field of the main table.
now when i query i need to join query with child table in a way that i picks up the table name from the column and join query with that table with concat function and then join on child id.
below is the structure of the table and also there values
CREATE TABLE IF NOT EXISTS `tbl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`tbl_type` enum('multi','gift','pledge') DEFAULT NULL,
`tbl_type_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `tbl` (`id`, `timestamp`, `tbl_type`, `tbl_type_id`) VALUES
(1, '2015-03-09 09:39:42', '', 1),
(2, '2015-03-09 22:43:23', 'multi', 2),
(3, '2015-03-09 23:26:38', 'gift', 1),
(4, '2015-03-10 09:46:15', 'pledge', 2);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tbl_gift` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `tbl_gift` (`id`, `amount`) VALUES
(1, '1231200'),
(2, '1231200');
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tbl_multi` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` float(255,0) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tbl_pledge` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `tbl_pledge` (`id`, `amount`) VALUES
(1, '10000'),
(2, '10200');
so this is simple hard code query
select * from tbl t left join tbl_gift g on g.id = t.tbl_type_id
but i want to make it dynamic i tried this
select * from tbl t left join (concat('tbl', '_', t.tbl_type)) g on g.id = t.tbl_type_id
should get the table which i need
(concat('tbl', '_', t.tbl_type))
but it get error
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('tbl', '_', t.tbl_type)) g on g.id = t.tbl_type_id LIMIT 0, 30' at line 1
The comments by Ankit and Usedby answered your question.
SQL does not allow you to provide dynamically constructed table names as you attempted. They provided you with two options: 1) Construct your query dynamically on the PHP side, then SQL see only the static table names or
2) Use the SQL PREPARE command to construct the dynamic table name and the EXECUTE SQL command to execute it.
Related
This is the code That is supposed to delete the student from the table.
but it it not working.
it only works when the table name is static.
public function delete_student($student_class,$school_session,$id){
$table_name = $student_class."_".$school_session."_student_record";
$pdo = KITE::getInstance('pdo');
$query = $pdo->prepare("DELETE FROM ".$table_name." WHERE `id` = ?");
$query->bindValue(1,$id);
$query->execute();
}
As I mentioned in a comment, a slash / is not permitted in the name of a table, column, function name, procedure name etc. Why then your query works when the name is statically typed is a mystery.
A quickly constructed demo that uses innodb tables with foreign keys and hopefully very little / no redundancy. If you have mysql running locally try running this in your gui ( such as heidi ) to get an idea of how it might be accomplished.
drop database if exists `demo_school_sessions`;
create database if not exists `demo_school_sessions`;
use `demo_school_sessions`;
drop table if exists `classes`;
create table if not exists `classes` (
`id` int(10) unsigned not null auto_increment,
`class` varchar(50) not null,
primary key (`id`)
) engine=innodb default charset=latin1;
insert into `classes` (`id`, `class`) values
(1, 'mathematics'),
(2, 'physics'),
(3, 'computing');
drop table if exists `sessions`;
create table if not exists `sessions` (
`id` int(10) unsigned not null auto_increment,
`session` varchar(50) not null,
primary key (`id`)
) engine=innodb default charset=latin1;
insert into `sessions` (`id`, `session`) values
(1, 'summer'),
(2, 'winter'),
(3, 'spring'),
(4, 'autumn');
drop table if exists `students`;
create table if not exists `students` (
`id` int(10) unsigned not null auto_increment,
`student` varchar(50) not null,
primary key (`id`)
) engine=innodb default charset=latin1;
insert into `students` (`id`, `student`) values
(1, 'bobby droptables'),
(2, 'sue select'),
(3, 'david delete'),
(4, 'valerie view'),
(5, 'peter procedure'),
(6, 'freddy function');
drop table if exists `year`;
create table if not exists `year` (
`id` int(10) unsigned not null auto_increment,
`year` varchar(9) not null default '2014/2015',
primary key (`id`)
) engine=innodb default charset=latin1;
insert into `year` (`id`, `year`) values
(1, '2014/2015'),
(2, '2015/2016'),
(3, '2016/2017'),
(4, '2017/2018'),
(5, '2018/2019'),
(6, '2019/2020');
drop table if exists `master`;
create table if not exists `master` (
`id` int(10) unsigned not null auto_increment,
`student` int(10) unsigned not null default '0',
`class` int(10) unsigned not null default '0',
`session` int(10) unsigned not null default '0',
`year` int(10) unsigned not null default '0',
primary key (`id`),
key `student` (`student`),
key `class` (`class`),
key `session` (`session`),
key `year` (`year`),
constraint `fk_year` foreign key (`year`) references `year` (`id`) on delete cascade on update cascade,
constraint `fk_class` foreign key (`class`) references `classes` (`id`) on delete cascade on update cascade,
constraint `fk_session` foreign key (`session`) references `sessions` (`id`) on delete cascade on update cascade,
constraint `fk_stud` foreign key (`student`) references `students` (`id`) on delete cascade on update cascade
) engine=innodb default charset=latin1;
insert into `master` (`id`, `student`, `class`, `session`, `year`) values
(1, 1, 3, 4, 1),
(2, 1, 1, 4, 1),
(3, 2, 2, 4, 1),
(4, 2, 3, 4, 1);
/* example to select records */
select * from `master` m
left outer join `students` s on s.id=m.student
left outer join `classes` c on c.id=m.class
left outer join `sessions` ss on ss.id=m.`session`
left outer join `year` y on y.id=m.`year`
where m.`class`=3 or m.`student`=1;
/* Example to delete a student */
delete from `students` where `id`=1;
/*
*/
Because of Foreign Key Dependencies if you delete a student from the student table all associated records from the master table would also be deleted as there is a cascade set for both update and delete. Care MUST be taken when using foreign keys like this because if you delete a record accidentally and there is a cascaded delete set on the key then all the associated records disappear!
We have the following two tables:
CREATE TABLE IF NOT EXISTS `gp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`amount` decimal(15,2) NOT NULL,
`user` varchar(100) NOT NULL DEFAULT '',
`status` tinyint(2) NOT NULL DEFAULT '1',
`ip` varchar(20) NOT NULL DEFAULT 'N/A',
`token` varchar(100) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `gp_logs` (
`id` int(11) NOT NULL,
`log` varchar(1000) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
We JOIN them, for statistics, but we do this rarely, since the data from the 2nd table is not used too often except when we need to verify things.
Considering that we have many queries per second, how can our query be optimized to use 1 INSERT query instead of two and to insert the correct id in the 2nd table (gp_logs) that was generated by the INSERT into table gp?
Right now, we do a combination of MYSQL with PHP:
mysqli_query($con,"INSERT INTO `gp` (amount,user) VALUES ('1234','1')");
$id = mysqli_insert_id($con);
mysqli_query($con,"INSERT INTO gp_logs(id,log) VALUES ('$id','some_data')");
We want to eliminate the requirement of PHP for getting the last inserted ID and to insert both entries by running a single INSERT query (with a JOIN).
Is it possible to select certain rows based on a category which matches it when there are multiple categories in the entry? It's hard to explain so I'll show you. The row I have in the database looks like this:
**article_title** | **article_content** | **category**
Article-1 | some content here | one,two,three,four
So my query looks like this:
$sql = mysqli_query($mysqli_connect, "SELECT * FROM table WHERE category='
preg_match(for example the word three)'");
Reason why I'm doing that is some articles will be available on multiple pages like page one and page three...so is there a way to match what I'm looking for through the entry in the database row?
You should use a more flexible database design. Create a separate table that holds the one-to-many relationships between (one) article and (many) categories:
CREATE TABLE IF NOT EXISTS `articles` (
`article_id` int(11) NOT NULL AUTO_INCREMENT,
`article_name` varchar(255) NOT NULL,
PRIMARY KEY (`article_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `articles` (`article_id`, `article_name`) VALUES
(1, 'Research Normalized Database Design');
CREATE TABLE IF NOT EXISTS `article_category` (
`article_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `article_category` (`article_id`, `category_id`) VALUES
(1, 1),
(1, 2);
CREATE TABLE IF NOT EXISTS `categories` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`category_name` varchar(255) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `categories` (`category_id`, `category_name`) VALUES
(1, 'Databases'),
(2, 'Normalization');
Querying then becomes as simple as:
SELECT
*
FROM
articles AS a
JOIN
article_category AS pivot ON a.article_id = pivot.article_id
WHERE
pivot.category_id = 2
Or do something like:
SELECT
*
FROM
articles AS a
JOIN
article_category AS pivot ON a.article_id = pivot.article_id
JOIN
categories AS c ON pivot.category_id = c.category_id
WHERE
c.category_name = 'Normalization'
I am trying to duplicate a page in the database and all related rows.
The problem I am having is because the page_group_id is an identifier for both tables. Is there any way of doing this without looping each of the new "page_groups" records?
pages (page_id, page_name, etc)
page_groups (page_group_id, page_id, etc)
page_group_items (page_group_id, item_id, etc)
UPDATE:
--
-- Table structure for table `pages`
--
CREATE TABLE IF NOT EXISTS `pages` (
`page_id` int(11) NOT NULL AUTO_INCREMENT,
`page_name` varchar(255) NOT NULL,
PRIMARY KEY (`page_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `pages`
--
INSERT INTO `pages` (`page_id`, `page_name`) VALUES
(1, 'My Page'),
(2, 'My other page');
-- --------------------------------------------------------
--
-- Table structure for table `page_groups`
--
CREATE TABLE IF NOT EXISTS `page_groups` (
`page_group_id` int(11) NOT NULL AUTO_INCREMENT,
`page_group_name` varchar(255) NOT NULL,
`page_id` int(11) NOT NULL,
PRIMARY KEY (`page_group_id`),
KEY `page_id` (`page_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `page_groups`
--
INSERT INTO `page_groups` (`page_group_id`, `page_group_name`, `page_id`) VALUES
(1, 'My Group', 1),
(2, 'My Group', 2);
-- --------------------------------------------------------
--
-- Table structure for table `page_group_items`
--
CREATE TABLE IF NOT EXISTS `page_group_items` (
`page_group_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
KEY `item_id` (`item_id`),
KEY `page_group_id` (`page_group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `page_group_items`
--
INSERT INTO `page_group_items` (`page_group_id`, `item_id`) VALUES
(1, 1),
(1, 2),
(1, 3),
(2, 1),
(2, 2);
Since you're replacing the only unique identifier in each table (the primary key) when copying, I can't see a way of doing it without adding temporary anchor columns to the tables, do the copy and remove them again. Something like this;
ALTER TABLE pages ADD originalpageid INT;
UPDATE pages set originalpageid=page_id;
ALTER TABLE page_groups ADD originalpagegroupid INT;
UPDATE page_groups SET originalpagegroupid=page_group_id;
INSERT INTO pages (page_name,originalpageid)
SELECT page_name,originalpageid FROM pages;
INSERT INTO page_groups (page_group_name,page_id,originalpagegroupid)
SELECT page_group_name,MAX(pages.page_id),originalpagegroupid
FROM page_groups
JOIN pages
ON page_groups.page_id=originalpageid
GROUP BY originalpageid,page_group_name,originalpagegroupid;
INSERT INTO page_group_items(page_group_id,item_id)
SELECT MAX(page_groups.page_group_id),item_id
FROM page_group_items
JOIN page_groups
ON page_group_items.page_group_id=originalpagegroupid
GROUP BY originalpagegroupid,item_id;
ALTER TABLE pages DROP COLUMN originalpageid;
ALTER TABLE page_groups DROP COLUMN originalpagegroupid;
An SQLfiddle to test with
If the use case is doing it all the time in the system, it may not be the solution you're looking for, but for manual intervention it should work well.
As always, always back your database up before running SQL from random strangers on the Internet :)
I am new in using advanced SQL queries and I am struggling with one query.
I have booking system created in php and it is using 4 tables:
site_days
site_timeslots
site_bookings
site_teams
each site_team is related to site_booking
each site_booking is related to site_timeslot
each site_timeslot is related to site_days
there can be more site_timeslots related to one site_day
there can be more site_bookings related to one site_timeslot
there can be more site_teams related to one site_bookings
you can create test tables with this sql:
-- Adminer 3.6.3 MySQL dump
SET NAMES utf8;
SET foreign_key_checks = 0;
SET time_zone = 'SYSTEM';
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `site_bookings`;
CREATE TABLE `site_bookings` (
`id` int(11) NOT NULL auto_increment,
`timeslot_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
INSERT INTO `site_bookings` (`id`, `timeslot_id`) VALUES
(1, 6443);
DROP TABLE IF EXISTS `site_days`;
CREATE TABLE `site_days` (
`id` int(11) NOT NULL auto_increment,
`date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
INSERT INTO `site_days` (`id`, `date`) VALUES
(85, '2013-04-01'),
(92, '2013-04-02');
DROP TABLE IF EXISTS `site_teams`;
CREATE TABLE `site_teams` (
`id` int(11) NOT NULL auto_increment,
`booking_id` int(11) NOT NULL,
`name` varchar(100) collate utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
INSERT INTO `site_teams` (`id`, `booking_id`, `name`) VALUES
(1, 1, 'Avengers'),
(2, 1, 'Big Five');
DROP TABLE IF EXISTS `site_timeslots`;
CREATE TABLE `site_timeslots` (
`id` int(11) NOT NULL auto_increment,
`day_id` int(11) NOT NULL,
`date` date NOT NULL,
`starts` time NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7152 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
INSERT INTO `site_timeslots` (`id`, `day_id`, `date`, `starts`) VALUES
(6443, 85, '2013-04-01', '08:00:00'),
(6444, 85, '2013-04-01', '08:10:00'),
(7098, 92, '2013-04-02', '08:00:00'),
(7099, 92, '2013-04-02', '08:10:00');
As a result I want to get ALL timeslots of table site_timeslots with few additional info:
- for each site_timeslot I want to know count of site_teams in all related bookings to that timeslot in total (for example if there are 2 site_bookings for that site_timeslot and each has 2 site_teams, then total count should be 4) and also count of related bookings.
I have tried this sql:
SELECT `site_teams`.`id` AS site_teams_id, `site_teams`.`name` AS site_teams_name, `site_teams`.`booking_id` AS site_teams_booking_id, `site_days`.`id` AS site_days_id, `site_days`.`date` AS site_days_date, `site_timeslots`.`id` AS site_timeslots_id, `site_timeslots`.`starts` AS site_timeslots_starts, `site_bookings`.`id` AS site_bookings_id, `site_bookings`.`timeslot_id` AS site_bookings_timeslot_id
FROM (`site_days`)
LEFT JOIN `site_timeslots` ON `site_timeslots`.`day_id` = `site_days`.`id`
LEFT JOIN `site_bookings` ON `site_bookings`.`timeslot_id` = `site_timeslots`.`id`
LEFT JOIN `site_teams` ON `site_teams`.`booking_id` = `site_bookings`.`id`
GROUP BY `site_teams`.`booking_id`
-> but i won't get timeslots which haven't got any site_bookings, please how I should alter this sql query to have in result:
site_timeslot per row
count of site_bookings related to that site_timeslot in new column 'count_of_site_bookings'
count of site_teams related to all site_bookings that are related to that site_timeslot in new column 'count_of_site_teams'
You can do this by LEFT JOINing starting on site_timeslots and then using COUNT on the 2 relevant fields to get the totals you are after
SELECT
sti.*,
COUNT(DISTINCT sb.id) AS count_of_site_bookings,
COUNT(DISTINCT ste.id) AS count_of_site_teams
FROM site_timeslots sti
INNER JOIN site_days sd
ON sd.id = sti.day_id
LEFT JOIN site_bookings sb
ON sb.timeslot_id = sti.id
LEFT JOIN site_teams ste
ON ste.booking_id = sb.id
GROUP BY sti.id
You can find this on SQL Fiddle http://sqlfiddle.com/#!2/1a253/2
I also did a previous version which used a subquery due to an incorrect assumption on my part, if you'd like to take a look at that for reference it's available also at http://sqlfiddle.com/#!2/9ccf2/10