I read here that I can include an argument inside COUNT, to return a calculated value. I'm trying the following but I'm missing something. Can you help? Thanks!
mysql_select_db(DATABASE_NAME, $connection);
$client = "demo/";
$result = mysql_query
(
"SELECT
COUNT(page_max > 126) AS completed
FROM " .SESSIONDB. "
WHERE client = '$client'
AND page = 'interaction.php'
"
);
if(mysql_error()) die(DIRECTORY_TITLE . " - Error DBA110 " . mysql_error());
// output THE QUERY
while($row = mysql_fetch_assoc($result))
{
echo $row['completed'];
}
Try
"SELECT
COUNT(*) AS completed
FROM " .SESSIONDB. "
WHERE client = '$client' AND page_max > 126
AND page = 'interaction.php'"
How about this
SELECT
SUM(CASE WHEN page_max > 126 THEN 1 ELSE 0 END) AS completed
FROM table
WHERE client = '$client'
AND page = 'interaction.php'
Or as Nicolò Martini said, move page_max to WHERE condition if you don't need total count of items.
This should do what you want:
SELECT COUNT(IF(page_max>126,1,NULL)) AS completed ....
COUNT counts the number of rows that aren't NULL. This expression turns anything where page_max is greater than 126 into 1 and anything that isn't into NULL.
That said, why not just move page_max to the WHERE condition?
Related
my table
This is my table i have to display the data using multiple where conditions. First i select using dms_expire_date,for this i got answer and i am using dms_doc_name in where conditions but i didn't got correct result.
I have tired so far.
]
See this picture if i use "or" in "where" i got testie not within this date.but if i use "and" in "where" i didn't got result for dms_expiry_date
See this picture
i don't know how to do this.please help to solve this problem.
SELECT * FROM `dms_document` WHERE dms_expire_date BETWEEN '2020-05-01' AND '2020-07-16' AND dms_doc_name = '' OR dms_category_id = '' OR dms_subcategory_id=''
I have tired in array also but i didn't result.
$this->db->select('*');
$this->db->join('dms_category as C', 'C.dms_category_id = D.dms_category_id', 'left outer');
$this->db->join('dms_sub_category as S', 'S.dms_subcategory_id = D.dms_subcategory_id', 'left outer');
$this->db->where('dms_expire_date >=', $newstart);
$this->db->where('dms_expire_date <=', $newend);
$this->db->where(array('dms_doc_name' =>$docname,'D.dms_category_id'=>$category,'D.dms_subcategory_id'=>$subcategory));
$data['documents']= $this->db->get('dms_document as D')->result_array();
try
SELECT *
FROM dms_document
WHERE dms_expire_date BETWEEN $newstart AND $newend
AND CASE WHEN $docname IS NULL THEN 1 = 1 ELSE dms_doc_name = $docname END
AND CASE WHEN $category IS NULL THEN 1 = 1 ELSE dms_category_id = $category END
AND CASE WHEN $subcategory IS NULL THEN 1 = 1 ELSE dms_subcategory_id = $subcategory END
--
edited. waiting for clearance.
if I get what you mean correctly, it is problem with understanding AND, OR, and the priority with brackets ()
--
if anyone want to use the fiddle, I have created the sample data for this issue
You can write OR using CodeIgniter's or_where() (v3 docs) or orWhere() (v4 docs).
//your initial query
$sql = "SELECT
*
FROM
`dms_document`
WHERE
dms_expire_date BETWEEN '2020-05-01' AND '2020-07-16'
AND dms_doc_name = ''
OR dms_category_id = ''
OR dms_subcategory_id=''";
//building the same query using CI
$this->db->select('*');
$this->db->from('dms_document');
$this->db->where('dms_expire_date >=', '2020-05-01');
$this->db->where('dms_expire_date <=', '2020-07-16');
$this->db->where('dms_doc_name', '');
$this->db->or_where('dms_category_id', '');
$this->db->or_where('dms_subcategory_id', '');
You can confirm the query this generates by running $this->db->_compile_select(); or $this->db->last_query(); (https://stackoverflow.com/a/6145021/1499877 for reference).
echo '<pre>';
var_dump($sql);
var_dump($this->db->_compile_select());
echo '</pre>';
die();
I believe this is causing anywhere from a 5 minute to 20 minute delay depending on the number of records. I need to translate it into a LEFT JOIN but need some help getting it there.
qry_arr = array(':bill_type' => "INT");
$sql = "update ".$billing_table." c set c.bill_type = :bill_type";
$sql .= " WHERE NOT EXISTS (SELECT s.abbreviation FROM state s WHERE s.abbreviation = c.out_location)";
$sql .= " and c.out_location != 'UNKNOWN' and c.out_location != ''";
UPDATE $billing_table c
LEFT JOIN state s ON s.abbreviation = c.out_location
SET c.bill_type = :bill_type
WHERE s.abbreviation IS NULL
AND c.out_location NOT IN ('UNKNOWN', '')
This is essentially the same as the syntax for a SELECT for the rows that don't match. See Return row only if value doesn't exist. Just replace SELECT ... FROM with UPDATE, and insert the SET clause before WHERE.
Make sure you have indexes on out_location and abbreviation.
I have this Perl code:
my $cmd = "
SELECT COUNT(id)
FROM tblUsers
WHERE UPPER(username) = UPPER(?) AND password = ?
";
db_connect();
my $sql = $dbh->prepare($cmd);
my $count = 2;
$sql->execute(
$args{login_username},
crypt($args{login_password}, $args{login_username})
) or die "SQL Error: ".$sql->errstr;
$sql->bind_columns(\$count);
$sql->fetch;
which is returning 0, but should be returning a 1
If I output the following:
$msg = "wrong username/password: $count;$args{login_username};$args{login_password};" . crypt($args{login_password}, $args{login_username});
I get:
wrong username/password: 0;skeniver;password;skh9dtk2bCasY
and the crypt part is exactly what I have in the database. Running the same values in MySQL returns a count of 1.
I really can't figure out what's going wrong here.
Does anyone else see something I'm missing?
Assuming your select returns a non 0 value and assuming that the column password in tblUsers has skh9dtk2bCasY for username=skeniver, Try
$sql->execute($args{login_username}, crypt($args{login_password},$args{login_username}))
or die "SQL Error: ".$sql->errstr;
$count = $sql->fetchrow_array();
Or, if there is a possibility that the query returns multiple rows then-
$sql->execute($args{login_username}, crypt($args{login_password},$args{login_username}))
or die "SQL Error: ".$sql->errstr;
while (($count) = $sql->fetchrow_array()){
print "Count is: $count\n";
}
Basically I do while two time to get main group & group value. Example
$group_query = $db->query("
SELECT opt_id, opt_type
FROM ads_options
WHERE opt_id = '" . intval($data['ad_id']) . "'
GROUP BY opt_type");
while ($group_data = $db->fetch($group_query)) {
$option_query = $db->query("
SELECT *
FROM ads_options
WHERE opt_id = '" . intval($data['ad_id']) . "'
AND opt_type ='" . $group_data['opt_type'] . "'
ORDER BY opt_id DESC");
while ($option_data = $db->fetch($option_query)) {
}
}
Output :
Size : S
M
L
Color : White
Black
Question :
How to join current queries above with single statement?
Update :
Current database structure
opt_id opt_type opt_name opt_price
1236 Size S 0
1236 Size M 1
1236 Color Black 1
1236 Color White 2
Something like this would get the unique combinations, may be of help
$group_query = $db->query("
SELECT
DISTINCT opt_id, opt_type, opt_size
FROM ads_options
WHERE opt_id = " . intval($data['ad_id']) . "
ORDER BY opt_type, opt_size");
If you are able to supply more details as to precisely what you are trying to achieve, and the full design of ads_options, then it would be easier to provide more specific advice
Also a minor note, if opt_id is numeric then you don't need single quotes (') around it within the query (so removed them in example)
EDIT
Something like the following would return you a list of id, type, and then as third field a comma-delimited list of values, if that's of more help
$group_query = $db->query("
SELECT
opt_id, opt_type, GROUP_CONCAT(opt_name) AS opt_names
FROM ads_options
WHERE opt_id = " . intval($data['ad_id']) . "
ORDER BY opt_type");
For more information on GROUP_CONCAT check out this link http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
I've no idea if PHP programatically has something to help with this, I tend to use Coldfusion so if anyone knows of a PHP version of doing the following then that seems to match what OP was asking for
<cfoutput query="qryAdOptions" group="opt_type">
#qryAdOptions.opt_type#
<cfoutput>
#qryAdOptions.opt_name#
</cfoutput>
</cfoutput>
http://bytes.com/topic/php/answers/11929-grouping-results-query#post50606 seems to suggest the following as potentially a match for the I posted above so may be useful
$answer = array();
while ($row = pg_fetch_array($results)) {
if (!isset($answer[$row["obj_type"]])) {
$answer[$row["obj_type"]] = array();
}
$answer[$row["obj_type"]][] = $row;
}
You then iterate over $answer. This would play nicely with
SELECT * FROM ads_options WHERE opt_id = ......
In one page, it should show records that has the following selected month from the drop down menu and it is set in the ?month=March
So the query will do this
$sql = "SELECT * FROM schedule WHERE month = '" . Clean($_GET['month']) . "' AND finished='0' ORDER BY date ASC";
But it shows records that has a value of 2 in the finished column and I don't want the query to include this.
I've tried
$sql = "SELECT * FROM schedule WHERE month = '" . Clean($_GET['month']) . "' AND finished='0' OR finished = '1' OR finished = '3' ORDER BY date ASC";
But it shows records on different months when it shouldn't be.
So basically I want the record to exclude the records that has the value of 2 in the record that will not be shown in the page.
Your first query should do what you want. Rows with finished = '2' should not be returned.
Ignoring that there is an error in your second query that you probably should fix:
$sql = "SELECT * FROM schedule WHERE month = '" . Clean($_GET['month']) .
"' AND (finished='0' OR finished = '1' OR finished = '3') ORDER BY date ASC";
The difference is parentheses around the OR clauses because AND binds more strongly than OR.
You could also achieve the same result more concisely using IN:
$sql = "SELECT * FROM schedule WHERE month = '" . Clean($_GET['month']) .
"' AND finished IN ('0', '1', '3') ORDER BY date ASC";
AND finished='0' OR finished = '1' OR finished = '3'
to
AND finished != 2
or
AND (finished = 0 OR finished = 1 OR finished = 3)