So I'm trying to find users from my database that don't have ANY rows in another table for the previous month, although it looks like my query is correct; I'm getting empty results?
public function __construct() {
parent::__construct();
//Set Payment Dates
$this->dates = array('1st', '8th', '15th', '25th');
//Which Month do the figures need submitting as
$this->monthPrev = date('F Y', strtotime(date('F Y')." -1 month"));
$this->currentMonth = date('F Y', strtotime('this month'));
}
public function getUnreportedQuarterlies()
{
$this->db->select('quarterly_figures.month, quarterly_figures.centre, users.name, users.email');
$this->db->from('quarterly_figures');
$this->db->join('users', 'users.name = quarterly_figures.centre', 'left');
$this->db->where("quarterly_figures.month", $this->monthPrev);
$this->db->where("quarterly_figures.centre IS NULL");
return $this->db->get()->result();
}
My database rows look something like so:
users
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
`address` varchar(45) DEFAULT NULL,
`owners_password` varchar(45) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `name`, `email`, `password`, `address`, `owners_password`) VALUES
(1, 'Aldridge', 'aldridge#website.co.uk', 'password', '127.0.0.1', 'password');
quarterly_figures
CREATE TABLE `quarterly_figures` (
`id` int(11) NOT NULL,
`centre` varchar(45) DEFAULT NULL,
`month` varchar(45) DEFAULT NULL,
`date` date DEFAULT NULL,
`direct_debits` varchar(45) DEFAULT NULL,
`money_paid` varchar(45) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `quarterly_figures` (`id`, `centre`, `month`, `date`, `direct_debits`, `money_paid`) VALUES
(1, 'Rugby', 'January 2019', '2019-01-01', '128', '3519.00');
The 'user' table has no relation with the 'quarterly_figures' table , If there is no relation returned data is not possible. you can insert an users.id into 'quarterly_figures' for each input.
Related
I use Codeigniter 3.1.11 and have some code which makes one big query to MySQL with an array. The time of a query with a limit of 30000 is about 9 seconds.
How can I reduce the request time? Maybe by using some indexes on my table, or do you know another method? If I need to use indexes, what indexes would I need to use and how can I use these indexes in my query on Codeigniter?
Code from model:
function rows_update() {
$query = $this->db->order_by('rating', 'DESC')->get_where('members', 'game_rating_and_balance_update_last_time <= now() - INTERVAL 1 DAY', '30000', '0');
$arrUpdateBatchData = [];
while ($row = $query->unbuffered_row('array'))
{
// some code here
$arrUpdateData = [
'UserID' => $row['UserID'],
'game_vault_balance' => $new_game_vault_balance,
'game_available_balance' => $new_game_available_balance,
'rating' => $rating_member,
'game_rating_and_balance_update_last_time' => date('Y-m-d H:i:s')
];
$arrUpdateBatchData[] = $arrUpdateData;
if (count($arrUpdateBatchData) > 500)
{
$this->db->update_batch('members', $arrUpdateBatchData, 'UserID');
$arrUpdateBatchData = [];
}
}
//update last items
if (count($arrUpdateBatchData) > 0)
{
$this->db->update_batch('members', $arrUpdateBatchData, 'UserID');
$arrUpdateBatchData = [];
}
return;
}
Raw query to MySQL with update_batch (I simply write only one row from an array):
UPDATE members SET game_vault_balance = CASE WHEN UserID = '9915075' THEN 803.60516004772 ELSE game_vault_balance END, game_available_balance = CASE WHEN UserID = '9915075' THEN 4.1253850908788 ELSE game_available_balance END, rating = CASE WHEN UserID = '9915075' THEN 0.24 ELSE rating END, game_rating_and_balance_update_last_time = CASE WHEN UserID = '9915075' THEN '2020-07-24 22:00:36' ELSE game_rating_and_balance_update_last_time END WHERE UserID IN('9915075')
Table structure:
CREATE TABLE `members` (
`id` int(10) UNSIGNED NOT NULL,
`UserID` varchar(64) NOT NULL,
`telegram_id` varchar(64) DEFAULT NULL,
`first_name` varchar(64) DEFAULT NULL,
`last_name` varchar(64) DEFAULT NULL,
`language` varchar(64) DEFAULT NULL,
`currency` varchar(64) DEFAULT NULL,
`status` varchar(64) DEFAULT NULL,
`rating` varchar(64) DEFAULT NULL,
`game_vault_balance` decimal(32,8) DEFAULT 0.00000000,
`game_available_balance` decimal(32,8) DEFAULT 0.00000000,
`game_rating_and_balance_update_last_time` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Indexes of this table:
ALTER TABLE `members`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UserID` (`UserID`) USING BTREE;
AUTO_INCREMENT for the members table:
ALTER TABLE `members`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
COMMIT;
I am a novice to MySQL
I have a database where I want to populate sets of records from 'sales' table where condition is sales is not delivered by comparing with 'deliveries' table of 'deliveries.reference_no'.
Both Tables has reference_no in common which is the invoice ref number.
I tried few SQL and got all common filed as it is and tried this one below but its displaying #1052 - Column 'date' in field list is ambiguous.
SELECT sales.id AS sid, date, reference_no, biller_name, customer_name, total_tax, total_tax2, total, internal_note FROM sales LEFT JOIN deliveries ON (sales.reference_no = deliveries.reference_no)
For more information below is my two table schema
Sales
CREATE TABLE IF NOT EXISTS `sales` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`reference_no` varchar(55) NOT NULL,
`warehouse_id` int(11) DEFAULT NULL,
`biller_id` int(11) NOT NULL,
`biller_name` varchar(55) NOT NULL,
`customer_id` int(11) NOT NULL,
`customer_name` varchar(55) NOT NULL,
`date` date NOT NULL,
`note` varchar(1000) DEFAULT NULL,
`internal_note` varchar(1000) DEFAULT NULL,
`inv_total` decimal(25,2) NOT NULL,
`total_tax` decimal(25,2) DEFAULT NULL,
`total` decimal(25,2) NOT NULL,
`invoice_type` int(11) DEFAULT NULL,
`in_type` varchar(55) DEFAULT NULL,
`total_tax2` decimal(25,2) DEFAULT NULL,
`tax_rate2_id` int(11) DEFAULT NULL,
`inv_discount` decimal(25,2) DEFAULT NULL,
`discount_id` int(11) DEFAULT NULL,
`user` varchar(255) DEFAULT NULL,
`updated_by` varchar(255) DEFAULT NULL,
`paid_by` varchar(55) DEFAULT 'cash',
`count` int(11) DEFAULT NULL,
`shipping` decimal(25,2) DEFAULT '0.00',
`pos` tinyint(4) NOT NULL DEFAULT '0',
`paid` decimal(25,2) DEFAULT NULL,
`cc_no` varchar(20) DEFAULT NULL,
`cc_holder` varchar(100) DEFAULT NULL,
`cheque_no` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
Deliveries
CREATE TABLE IF NOT EXISTS `deliveries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`time` varchar(10) NOT NULL,
`reference_no` varchar(55) NOT NULL,
`customer` varchar(55) NOT NULL,
`address` varchar(1000) NOT NULL,
`note` varchar(1000) DEFAULT NULL,
`user` varchar(255) DEFAULT NULL,
`updated_by` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
Currently I have a CI program and I am doing like this no Luck what I want to populate
CI PHP
function getdatatableajax()
{
if($this->input->get('search_term')) { $search_term = $this->input->get('search_term'); } else { $search_term = false;}
$this->load->library('datatables');
$this->datatables
->select("sales.id as sid, date, reference_no, biller_name, customer_name, total_tax, total_tax2, total, internal_note")
->from('sales');
$this->datatables->add_column("Actions",
"<center><a href='#' title='$2' class='tip' data-html='true'><i class='icon-folder-close'></i></a> <a href='#' onClick=\"MyWindow=window.open('index.php?module=sales&view=view_invoice&id=$1', 'MyWindow','toolbar=0,location=0,directories=0,status=0,menubar=yes,scrollbars=yes,resizable=yes,width=1000,height=600'); return false;\" title='".$this->lang->line("view_invoice")."' class='tip'><i class='icon-fullscreen'></i></a>
<a href='index.php?module=sales&view=add_delivery&id=$1' title='".$this->lang->line("add_delivery_order")."' class='tip'><i class='icon-road'></i></a>
<a href='index.php?module=sales&view=pdf&id=$1' title='".$this->lang->line("download_pdf")."' class='tip'><i class='icon-file'></i></a>
<a href='index.php?module=sales&view=email_invoice&id=$1' title='".$this->lang->line("email_invoice")."' class='tip'><i class='icon-envelope'></i></a>
</center>", "sid, internal_note")
->unset_column('sid')
->unset_column('internal_note');
echo $this->datatables->generate();
}
Wow, no one answered this yet? Strange.
Your error is because the date field is in both tables. You have to specify which table you want to select date from. So you must write either sales.date or deliveries.date. This goes with the rest of them, once you fix sales.date, your next field reference_no will generate the same error. If you want data from BOTH tables you'll need to assign aliases to them as you did with the first column.
sales.id AS sid, sales.date AS sales_date, deliveries.date AS deliveries_date etc...
I'm writing code for a school transcript system. However, I'm stuck in joining the tables which are the courses table I named 'causes', courses registered table I named 'courses_registered' and the students table 'students' actually the join works, but the problem is that data are repeated in multiples depending on how many data rows that are on the courses_registered table for example, if have 2 courses registered, I get 4 rows echoed out from all tables instead of two. so my question is, how can i join these three tables perfectly without data being repeated, when i loop through the data. this is the table structure for the three tables.
--
-- Table structure for table `courses`
--
CREATE TABLE IF NOT EXISTS `courses` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`course_code` varchar(255) NOT NULL,
`course_title` varchar(255) NOT NULL,
`cl` int(255) NOT NULL,
`level` int(255) NOT NULL,
`session` varchar(255) NOT NULL,
`semester` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `courses`
--
INSERT INTO `courses` (`id`, `course_code`, `course_title`, `cl`, `level`, `session`, `semester`) VALUES
(1, 'GSS 111', 'Use of English', 3, 1, '2009/2010', '1'),
(2, 'GSS 112', 'Nigerian History', 2, 1, '2009/2010', '1');
--
-- Table structure for table `courses_registered`
--
CREATE TABLE IF NOT EXISTS `courses_registered` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`course_id` int(255) NOT NULL,
`student_id` int(255) NOT NULL,
`score` int(255) NOT NULL,
`grade` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `courses_registered`
--
INSERT INTO `courses_registered` (`id`, `course_id`, `student_id`, `score`, `grade`) VALUES
(1, 1, 2, 60, 'B'),
(2, 2, 2, 80, 'A');
-- --------------------------------------------------------
--
-- Table structure for table `students`
--
CREATE TABLE IF NOT EXISTS `students` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`regno` varchar(255) NOT NULL,
`college` varchar(255) NOT NULL,
`dept` varchar(255) NOT NULL,
`level` varchar(255) NOT NULL,
`fname` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`no_of_semesters` int(255) NOT NULL,
`gender` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
`age` int(255) NOT NULL,
`mstatus` varchar(255) NOT NULL,
`nationality` varchar(255) NOT NULL,
`religion` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `students`
--
INSERT INTO `students` (`id`, `regno`, `college`, `dept`, `level`,
`fname`, `lname`, `no_of_semesters`, `gender`, `dob`, `age`,
`mstatus`, `nationality`, `religion`, `address`, `email`, `phone`)
VALUES
(2, 'MOUAU 09/14508', 'CEET', 'Electrical Electronics Engineering',
'1', 'Nnamdi', 'Okoro', 2, 'Male', '24-07-1989', 25, 'Single',
'Nigerian', 'christian', 'Okpu Umiobo road, Aba',
'nokoro#gmail.com', '09056733333');
Then this is the query
<?php
$sql = "
SELECT c.id as course_id
, c.course_code
, c.course_title
, c.cl
, c.level
, c.session
, c.semester
, r.id as rid
, r.course_id
, r.student_id
, r.score
, r.grade
, s.id
, s.regno
, s.fname
, s.lname
, s.no_of_semesters
FROM courses_registered r
JOIN courses c
ON r.course_id = course_id
JOIN students s
ON s.id = r.student_id
WHERE s.id = '$id'
";
$result = mysqli_query($con,$sql) or die ('Could not show students records.'. mysqli_error($con) );
if (mysqli_num_rows($result) > 0 ){
//echo mysqli_num_rows($result);
while($row = mysqli_fetch_array($result) ){
$score[] = $row['score'];
$course_code[] = $row['course_code'];
$course_title[] = $row['course_title'];
$cl[] = $row['cl'];
$grade[] = $row['grade'];
}
Try change this
ON r.course_id = course_id
to
ON r.course_id = c.id
This is my table:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(20) NOT NULL default '',
`pass` varchar(32) NOT NULL default '',
`lang` varchar(2) default NULL,
`locale` varchar(2) default NULL,
`pic` varchar(255) default NULL,
`sex` char(1) default NULL,
`birthday` date default NULL,
`mail` varchar(64) default NULL,
`created` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mail` (`mail`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;
And this is my query:
$query = "INSERT IGNORE INTO `users` (`name`, `mail`, `birthday`, `lang`, `locale`, `sex`, `pic`) VALUES ('".$name."', '".$email."', '".date_format($birthdaynew, 'Y-m-d H:i:s')."', '".substr($locale, 0, 2)."', '".substr($locale, -2, 2)."', '".$sex."', 'pic/".$uid.".jpg')";
$rows = mysql_query($query) or die("Failed: " . mysql_error());
$_SESSION['id'] = mysql_insert_id(); // I have tryed also mysql_insert_id($db_con) where $db_con is the link to db.
$_SESSION['name'] = $name;
$_SESSION['name'] contains correctly the name but $_SESSION['id'] contains 0.
Why ?
I'm going crazy!
Is there a particular reason why you are using INSERT IGNORE?
If you use INSERT IGNORE, then the row won't actually get inserted if there is a duplicate key (PRIMARY or UNIQUE), or inserting a NULL into a column with a NOT NULL constraint.
Referring to the pass column, as you have not defined anything to insert into it, and it has NOT NULL constraint.
EDIT:
Referring also to the mail column, as you have a UNIQUE constraint on it.
I'm working on a codeigniter project and I'm trying to troubleshoot a sql issue. I have a query that updates a date field in my table and it's not updating it at all.
I have this table
CREATE TABLE `Customer` (
`customer_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(55) NOT NULL DEFAULT '',
`last_name` varchar(55) NOT NULL DEFAULT '',
`city` varchar(255) DEFAULT '',
`state` char(2) DEFAULT '',
`zip` int(5) DEFAULT NULL,
`title` varchar(255) NOT NULL DEFAULT '',
`image` varchar(255) DEFAULT '',
`blurb` blob,
`end_date` date DEFAULT NULL,
`goal` int(11) DEFAULT NULL,
`paypal_acct_num` int(11) DEFAULT NULL,
`progress_bar` enum('full','half','none') DEFAULT NULL,
`page_views` int(11) NOT NULL DEFAULT '0',
`total_pages` int(11) NOT NULL DEFAULT '0',
`total_conversions` int(11) NOT NULL DEFAULT '0',
`total_given` int(11) NOT NULL DEFAULT '0',
`conversion_percentage` int(11) NOT NULL DEFAULT '0',
`avg_contribution` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`customer_id`)
) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
and when I run this query to insert data, it runs fine and sets the date to 2012-11-01
INSERT INTO `Customer` (`first_name`, `last_name`, `end_date`) VALUES ('John', 'Smith2', '2012-11-01');
Then I get the customer_id and try to run this query
UPDATE `Customer` SET `end_date` = '2012-14-01' WHERE `customer_id` = '18';
and it sets the date end_date field to 0000-00-00.
Why is it changing the end date to 0000-00-00 rather than 2012-14-01?
2012-14-01 is first day of fourteenth month :)
(so its invalid date, thus casted to 0000-00-00 and Data truncated for column 'end_date' at row 1 warning was returned by mysql, which you can see by querying SHOW WARNINGS to mysql immediately after badly behaving query)
2012-01-14 is 14th of January.
use this:
UPDATE `Customer` SET `end_date` = date('Y-m-d') WHERE `customer_id` = '18';
Use date function to update this field.