MySQL query - joining two tables producing duplicate results - php

I'm running the following MySQL query in PHP.
"SELECT *
FROM `challenges`,`verifications`
WHERE (`challenges`.`user_id`='".$this->record['id']."' OR `challenges`.`opponent_id`='".$this->record['id']."')
AND `challenges`.`is_verified`='0'
AND (`challenges`.`status`='in-progress' OR `challenges`.`status`='pending')
AND
(
(`verifications`.`user_id`='".$this->record['id']."' OR `verifications`.`opponent_id`='".$this->record['id']."')
AND (`verifications`.`user_verified`!=NULL AND `verifications`.`opponent_verified`=NULL)
)
LIMIT 100";
This query is returning duplicate records for some reason. If anyone has any insights, I would greatly appreciate it.
Here is the structure for the two tables (challenges and verifications):
Challenges Table:
CREATE TABLE `challenges` (
`id` int(11) NOT NULL auto_increment,
`wager` int(11) NOT NULL,
`type` varchar(255) NOT NULL,
`user_id` int(11) NOT NULL,
`opponent_id` int(11) NOT NULL,
`start_date` date NOT NULL,
`date_created` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`start_time` time NOT NULL,
`is_verified` tinyint(1) NOT NULL default '0',
`status` varchar(255) NOT NULL default 'pending',
`winner_id` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
Verifications Table:
CREATE TABLE `verify` (
`id` int(11) NOT NULL auto_increment,
`user_id` int(11) NOT NULL,
`opponent_id` int(11) NOT NULL,
`challenge_id` int(11) NOT NULL,
`user_verified` int(11) default NULL,
`opponent_verified` int(11) default NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `challenge_id` (`challenge_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;
Thanks for your help, and if you need any more info please let me know.

You have to add condition:
challenges.id = verify.challenge_id
to where clause as below
"SELECT *
FROM `challenges`,`verifications`
WHERE `challenges`.`id` = `verify`.`challenge_id`
AND (`challenges`.`user_id`='".$this->record['id']."'
OR `challenges`.`opponent_id`='".$this->record['id']."')
AND `challenges`.`is_verified`='0'
AND (`challenges`.`status`='in-progress' OR `challenges`.`status`='pending')
AND ( (`verifications`.`user_id`='".$this->record['id']."'
OR `verifications`.`opponent_id`='".$this->record['id']."')
AND (`verifications`.`user_verified`!=NULL
AND `verifications`.`opponent_verified`=NULL)
)
LIMIT 100";
or using ANSI-92
"SELECT *
FROM `challenges` as `challenges`
JOIN `verifications` as `verifications` on `challenges`.`id` = `verify`.`challenge_id`
WHERE (`challenges`.`user_id`='".$this->record['id']."' OR `challenges`.`opponent_id`='".$this->record['id']."')
AND `challenges`.`is_verified`='0'
AND (`challenges`.`status`='in-progress' OR `challenges`.`status`='pending')
AND
(
(`verifications`.`user_id`='".$this->record['id']."' OR `verifications`.`opponent_id`='".$this->record['id']."')
AND (`verifications`.`user_verified`!=NULL AND `verifications`.`opponent_verified`=NULL)
)
LIMIT 100";

Related

"a symbol name was expected" error trying to create a table in phpMyAdmin

I am trying to create a table in a database in phpMyAdmin and I keep getting the "a symbol name was expected" error and I cannot figure out what is going on. Is my syntax wrong? I am new to this and I'm at a loss.
Column names, table names should be surrounded by backticks(``)
CREATE TABLE IF NOT EXISTS `sales` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`item` varchar(50) NOT NULL,
`date` varchar(50) NOT NULL,
`amount` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
Or you can go without backticks as well:
CREATE TABLE IF NOT EXISTS sales (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
item varchar(50) NOT NULL,
date varchar(50) NOT NULL,
amount int(11) NOT NULL,
PRIMARY KEY (id)
)
Your code is wrong , So here is the correct Code :
CREATE TABLE IF NOT EXISTS `sales` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(50) CHARACTER SET utf8 NOT NULL,
`item` VARCHAR(50) CHARACTER SET utf8 NOT NULL,
`date` VARCHAR(50) NOT NULL,
`amount` int(11) NOT NULL
)
You used ' ' sign in your column properties. But mySQL allow you to use `` sign.
CREATE TABLE IF NOT EXISTS `sales` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`item` varchar(50) NOT NULL,
`date` varchar(50) NOT NULL,
`amount` int(11) NOT NULL,
PRIMARY KEY (`id`)
);

Want to populate sets of records from sales table by joining deliveries

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...

do query in another query, if another query not exists return 0 and compare value between 2 query

I have searched over and over but still can't write a correct query that actually work ! :|
I write this one and it seems ok but it's dosen't worked...
select
s.surf_id,
s.surf_dailyuser,
s.surf_url,
s.surf_cpc,
(if exists(
select surfed_count from `surfed` where s.surf_id = surfed_site and surfed_date = 'today'
) then select surfed_count as surfedcount;
else select 0 as surfedcount; end if
)
from `surfs` s where s.surf_status = 1 and surfedcount < s.surf_dailyuser order by s.surf_rand limit 1
any suggestion will be a big help :)
tables are like this
surfs
CREATE TABLE IF NOT EXISTS `surfs` (
`surf_id` int(11) NOT NULL,
`surf_user` int(11) NOT NULL,
`surf_title` varchar(128) CHARACTER SET latin1 NOT NULL,
`surf_url` varchar(500) CHARACTER SET latin1 NOT NULL,
`surf_dailyuser` int(11) NOT NULL,
`surf_cpc` int(11) NOT NULL,
`surf_status` int(11) NOT NULL,
`surf_date` varchar(32) NOT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
surfed
CREATE TABLE IF NOT EXISTS `surfed` (
`surfed_id` int(11) NOT NULL,
`surfed_code` int(11) NOT NULL,
`surfed_user` int(11) NOT NULL,
`surfed_site` int(11) NOT NULL,
`surfed_count` int(11) NOT NULL,
`surfed_date` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
You can use CASE statement as below
select
s.surf_id,
s.surf_dailyuser,
s.surf_url,
s.surf_cpc,
CASE WHEN
(select surfed_count from `surfed` where s.surf_id = surfed_site and surfed_date = 'today') = 1 then (select surfed_count as surfedcount)
ELSE 0 END AS surfedcount
from `surfs` s where s.surf_status = 1 and surfedcount < s.surf_dailyuser order by s.surf_rand limit 1

creating triggers with MySQL

Two tables: users and messages
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(10) NOT NULL,
`password` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
`verifystring` varchar(20) NOT NULL,
`active` tinyint(4) NOT NULL,
`usertype` tinyint(4) NOT NULL,
`img` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
CREATE TABLE IF NOT EXISTS `messages` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`topic_id` int(11) NOT NULL,
`subject` varchar(100) NOT NULL,
`body` text NOT NULL,
`img` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `topic_id` (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;
trigger:
CREATE TRIGGER `updateimg` AFTER UPDATE ON `users`
FOR EACH ROW begin
update messages set img = new.img where messages.user_id = users.id;
end
img field is keeping the name of the image user has uploaded.
How can i copy the value img from table users to table messages when it is updated?
Thats should do it:
CREATE TRIGGER update AFTER UPDATE ON table1
for each ROW
begin
update table2 set y = new.y where table2.user_id = new.id;
end

How do I select and match from multiple tables?

This is my table layout:
-- Table structure for table `areas`
CREATE TABLE IF NOT EXISTS `areas` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`country` varchar(20) NOT NULL,
`city` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- Table structure for table `matches`
CREATE TABLE IF NOT EXISTS `matches` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`view_id` bigint(20) unsigned NOT NULL,
`status` enum('h','n') NOT NULL,
`exp_date` date NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- Table structure for table `users`
CREATE TABLE IF NOT EXISTS `users` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`limit_age` varchar(5) NOT NULL DEFAULT '18:30',
`limit_gender` varchar(2) DEFAULT NULL,
`notifications` int(11) NOT NULL DEFAULT '0',
`name` varchar(30) NOT NULL,
`email` varchar(40) NOT NULL,
`image_big` varchar(120) NOT NULL,
`image_small` varchar(120) NOT NULL,
`crop_data` int(11) DEFAULT NULL,
`visible` tinyint(1) NOT NULL DEFAULT '0',
`age` int(11) DEFAULT NULL,
`registered_at` datetime NOT NULL,
`views` bigint(20) unsigned NOT NULL DEFAULT '0',
`hots` bigint(20) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
I will try to explain this better:
I have a given ID.
I would like to select one entry from users which is not the ID i have given
AND which user_id does not exist in matches
AND has visible = 1
AND where any country + city matches the given users country + city
Is this the correct way to do it (12 is an example of an given ID):
SELECT *
FROM users a
INNER JOIN areas ON areas.user_id = a.id
WHERE a.id NOT IN (SELECT user_id FROM matches)
AND NOT a.id = '12'
AND a.limit_age = '18:30'
AND a.visible = '1'
AND areas.country = 'sverige'
AND areas.city = 'gbg'
Sorry for the confusion :)
Ok, I'll make an attempt at this:
SELECT *
FROM users a
INNER JOIN areas ON areas.user_id = a.id
WHERE a.id NOT IN (SELECT user_id FROM matches)
AND a.visible = '1'
AND a.limit_age = '18:30'
AND a.limit_gender = 'f'
AND areas.country = ?
AND areas.city = ?;
This is SELECTing from "users", and returning a result only if that user also has an entry in the "areas" table. The first item in the WHERE clause ensures that a row will not be returned if the users.id (a.id) is found in the user_id field on the "matches" table. Next, I added checks for visible = 1, limit_age, and limit_gender as specified in his attempt. Finally, I left country and city parameterized so that they can be added as parameters in the php code. If anything that should give you a starting point.

Categories