I'm trying to return a count from mysql. My code is below
$number_of_options_sql = tep_db_query("SELECT COUNT( * ) FROM
(select sum(options_id) as total from products_attributes
where products_id='".$products_id."' group by options_id) as total");
$number_of_options_result = tep_db_fetch_array($number_of_options_sql);
When I run this query in Phpmyadmin, it shows the result with COUNT(*) at the table heading. I'm getting the correct result, the query works for me, I just can't print it out on the screen.
I've tried returning the value the following ways and neither print anything on the screen:
echo $number_of_options_result[COUNT( * )];
echo $number_of_options_result[total];
Use AS field_name after COUNT(*)
$number_of_options_sql = tep_db_query("SELECT COUNT(*) AS field_name FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) as total");
To print:
echo $number_of_options_result['field_name'];
(Replace "field_name" with any relevant name of your choice)
Your query is assigning an alias to the table/query not the column. use this one below:
$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) a");
$number_of_options_result = tep_db_fetch_array($number_of_options_sql);
Also looks like you want to know count of distinct options id for a product_id, I would rewrite the query as follows:
$number_of_options_sql = tep_db_query("SELECT COUNT(DISTINCT options_id) as total FROM products_attributes WHERE products_id='".$products_id."'");
Just edit your query to
SELECT COUNT(*) as count FROM ....
then it will be stored like 'count' and you can print it the $number_of_options_result[count]; way.
put in a variable "total"
$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total
then it works
echo $number_of_options_result['total'];
Related
I am trying to select added value "state" with newest date from my table, but only if left join table object is visible. And only once per property and unit in.
What i have done so far:
SELECT propertyUnitEnergyStates.id,
propertyUnitEnergyStates.property_id,
propertyUnitEnergyStates.unit_id,
propertyUnitEnergyStates.type,
propertyUnitEnergyStates.state,
propertyUnitEnergyStates.date,
propertyUnits.visible
FROM propertyUnitEnergyStates
LEFT JOIN propertyUnits
ON propertyUnits.property_id = $propertyID
WHERE propertyUnitEnergyStates.property_id = $propertyID
AND propertyUnitEnergyStates.type = '$name'
AND propertyUnits.visible = 1
GROUP BY propertyUnitEnergyStates.unit_id
ORDER BY propertyUnitEnergyStates.date DESC
What I am getting now is result where every propertyUnits.visible is 1. Even if in table is set to zero.
Object from propertyUnits. As you can see the value visible is 0 but i am getting 1.
Right now i noticed that, the "state" value which i want to be the newest is not the newest.
As you can see i have in my result for unit_id 5 value 853, but in the table propertyUnitEnergyStates is the newest value 400.
Okay. Let's try like this.
WITH ranked_state AS (
SELECT us.*, ROW_NUMBER() OVER (PARTITION BY unit_id ORDER BY date DESC) AS rn
FROM propertyUnitEnergyStates us
WHERE us.type = '$name' AND us.property_id = $propertyID
)
SELECT ranked_state.id,
ranked_state.property_id,
ranked_state.unit_id,
ranked_state.type,
ranked_state.state,
ranked_state.date,
pu.visible
FROM ranked_state
LEFT JOIN propertyUnits pu
ON ranked_state.property_id = pu.property_id AND pu.visible = 1
WHERE rn = 1
If I explain this query.. First, regarding the rows that meet the given condition(ex: us.type="$name", us.property_id=$propertyID), the rows with the same unit_id are ordered by date.
After then do LEFT JOIN.
I try different options, but I still can't get the result. It still ignores the visible attribute and does not return the last record by date.
Here is my last try:
$query = "SELECT UniEne.id,
UniEne.property_id,
UniEne.unit_id,
UniEne.type,
UniEne.state,
UniEne.date,
propUni.visible
FROM
(SELECT * FROM propertyUnitEnergyStates WHERE type = '$name' AND property_id = $propertyID ORDER BY date DESC) AS UniEne
INNER JOIN (SELECT * FROM propertyUnits WHERE property_id= $propertyID AND visible = 1) as propUni
WHERE UniEne.property_id = $propertyID GROUP BY UniEne.unit_id";
Result is:
But value "state" is not correct. The last inserted have in unit_id(1) value 7000..
I am using the query below to get all results and then then group them. It all works well. I now have multiple rows of identical data but with a different price.
How can I do the same query but get just the row with the cheapest price when all other data is identical. I have spent ages but no joy at all. Please help.
$results = $wpdb->get_results($wpdb->prepare("
SELECT *,
group_concat(date,':',SUBSTRING_INDEX(flights,'|',2),':',price,':',board,':',$tablename.id separator ',') as itemx
FROM $tablename
WHERE post_type = 'product'
GROUP BY brochure
LIMIT 20
"));
Presumably, you want something like this:
SELECT t.*,
FROM $tablename t
WHERE t.post_type = 'product' AND
t.price = (SELECT MIN(t2.price)
FROM $tablename t2
WHERE t2.post_type = 'product' AND
t2.brochure = t.brochure
);
This is at least a correctly constructed query that gets the minimum price for each brochure.
So I have a table where some of the products repeat with but have a different value on number of clicks.
name ---- clicks
iPhone 4
Samsung 2
iPhone 1
Samsung 5
my select function is :
$select_table2 = 'SELECT * FROM `mytable`'; //WHERE NAME IS THE SAME
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
I need this output:
iPhone 5
Samsung 7
I don't want to merge the same rows because they have one more column that is different. So please do not suggest simply to merge them and update the clicks...
UPDATE:
$pull_request = 'SELECT SUM(e.product_clicks),e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e GROUP BY e.product_id LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id';
I tried it like this but it's not working
use sum() and also GROUP BY name to get desired output.
$select_table2 = 'SELECT name,SUM(clicks) FROM `mytable` GROUP BY name';
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
while will produce,
iPhone 5
Samsung 7
For more info
SUM()
GROUP BY
EDIT
Group by should come after join.
$pull_request = 'SELECT SUM(e.product_clicks) as clicks,e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e
LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id
GROUP BY e.product_id';
You want to perform a SUM command by group
$query = "SELECT `name`,SUM(`clicks`) FROM `mytable` GROUP BY `name`";
Edit: The other answer was more complete than mine. I forgot to select name field. Added.
What you need is an aggregate function for suming the clicks [SUM(clicks)], and a Group By clause for defining the classification criteria [GROUP BY name].
The other answers where wrong in the sense that are assuming that by changing the select field list adding the aggregate 'SUM', the associative references (eg: index strings of the $row array ) remains the same, the correct query would be:
$select_table2 = 'SELECT name, SUM (clicks) AS clicks FROM mytable GROUP BY name';
Note the alias on SUM(clicks) AS clicks, so the fields returned in the array $row keep their indexes (clicks, names... instead of 'SUM(clicks)')
And the rest is basically the same.
Cheers!
Try :
$select_table2 = 'SELECT name, SUM (clicks) FROM mytable GROUP BY name';
This code is looking for the rows that contain the same value in "slug" column and grouping them if they are found more than once.
UPDATED CODE:
$sql = " SELECT *,
COUNT(slug)
FROM cars
GROUP BY slug
HAVING ( COUNT(slug) > 1 )";
$q = $this->db->query($sql);
return $q;
The problem is that instead of:
blue-volkswagen-2001
blue-volkswagen-2001
red-toyota-1989
red-toyota-1989
red-toyota-1989
green-mercedes-50
green-mercedes-50
I am getting this:
blue-volkswagen-2001
red-toyota-1989
green-mercedes-50
Any idea what am I doing wrong and why only the first row is grabbed instead of all duplicates?
I have asked this question on CodeIgniter forum, but they didn't know how to do this so I can accept a custom SQL query from some SQl guru instead of Active Record, because that's probably not possible to achieve with Active Record.
You can use INNER JOIN with a subquery to achieve this.
$query = "SELECT a.*, b.total_count FROM cars a INNER JOIN (SELECT slug, count(*) as total_count FROM cars GROUP BY slug HAVING count(slug) > 1 ) b ON a.slug = b.slug WHERE b.total_count > 1";
$output = $this->db->query($query );
Do index slug column to improve performance.
This will give the output like the way you want.
Hope this helps :-)
Using subquery
SELECT * FROM `cars` WHERE slug IN ( SELECT slug FROM vehicle GROUP BY slug
HAVING ( COUNT(slug) > 1 ) )
SQLFIDDLE
SELECT MAX(slug)
FROM cars
GROUP BY slug
HAVING COUNT(slug) > 1
I have two tables which I have joined. The query looks like this:
SELECT *, AVG(rate)
FROM comments c
LEFT JOIN supps s
on c.tutorialid = s.tutid
WHERE category = 'Protein'
GROUP BY tutorialid
ORDER BY $orderby $sort LIMIT $startrow,$limit";
And I have the code below to get the total comments:
//find the number of comments
$commentNum = mysql_num_rows($result);
When I use echo $commentNum, it displays the total for all comments on every row for example if I had:
echo "".$row['title'] ."<br>";
echo $commentNum .
It would give me the total comments for all the posts rather the total for each individual post. Can anyone tell me what I have got wrong? How can I get total comment for each post?
I would try adding COUNT(*) in your initial SELECT. So your query would read
SELECT *, COUNT(*), AVG(rate)
FROM comments c
LEFT JOIN supps s
ON c.tutorialid = s.tutid
WHERE category = 'Protein'
GROUP BY tutorialid
ORDER BY $orderby $sort LIMIT $startrow,$limit";