Hello the group by on MYSQL is working but on PHP query i not working.
If i remove Group By from PHP is working but i dont take correct results.
MYSQL
SELECT _o.Ora,_u.Fname,_u.Sname,_u.Phone,_o.Name1,_o.Name2,_o.Name3,_o.Name4,_o.Name5,_o.Name6,_o.PaymentType,_o.FinalPrice
FROM _orders as _o,_users as _u WHERE _o.ShopName='ISAAK' AND _o.HmerominiaParagelias='13/12/2018' AND _o.UserID=_u.Username
GROUP BY _o.OraParagelias IN (SELECT MAX(OraParagelias) FROM _orders) ORDER BY _o.Ora DESC;
Result
PHP Code:
<?php
include_once 'connect.php';
$ShopName= $_POST['ShopName'];
$HmerominiaParagelias= $_POST['HmerominiaParagelias'];
$sql = "SELECT _o.Ora,_u.Fname,_u.Sname,_u.Phone,_o.Name1,_o.Name2,_o.Name3,_o.Name4,_o.Name5,_o.Name6,_o.PaymentType,_o.FinalPrice
FROM _orders as _o,_users as _u WHERE _o.ShopName='$ShopName' AND _o.HmerominiaParagelias='$HmerominiaParagelias' AND _o.UserID=_u.Username
GROUP BY _o.OraParagelias IN (SELECT MAX(OraParagelias) FROM _orders) ORDER BY _o.Ora DESC";
$result = $dbcon->query($sql);
if($result->num_rows> 0) {
while ($row = $result->fetch_assoc()){
echo "\nΏρα: ".$row["Ora"]."\nΌνομα: ".$row["Fname"]."\nΕπώνυμο: ".$row["Sname"]."\nΤηλ.: ".$row["Phone"]."\n".$row["Name1"]."\n".$row["Name2"]."\n".
$row["Name3"]."\n".$row["Name4"]."\n".$row["Name5"]."\n".$row["Name6"]."\nΤρόπος Πλήρ.: ".$row["PaymentType"]."\nΤελικό Ποσό: ".$row["FinalPrice"].
"€?";
}
} else{
echo "no_orders_found?";
}
?>
[![enter image description here]
As result i take: no_orders_found
Any solution on how to fix group by on php?
Consider a compliant ANSI SQL query using explicit JOIN between tables. Specifically, join on an aggregate query to connect user unit level data to their corresponding max value to return more than two users. Below assumes UserID is the unique value to use for joining (adjust as needed).
Likely, the reason for differences of query runs is the PHP DBI-API (mysqli, pdo, etc.) does not allow the strange (newer?) GROUP BY ... IN() whereas MySQL workbench apparently does, maybe with a specific setting turned on.
SELECT _o.Ora, _u.Fname, _u.Sname, _u.Phone, _o.Name1, _o.Name2, _o.Name3,
_o.Name4, _o.Name5, _o.Name6, _o.PaymentType, _o.FinalPrice
FROM _orders as _o,
INNER JOIN _users as _u
ON _o.UserID = _u.Username
INNER JOIN
(SELECT UserID, MAX(OraParagelias) AS Max_OraParagelias
FROM _orders
GROUP BY userID
) AS m
ON _o.userID = m.userID AND _o.OraParagelias = m.Max_OraParagelias
WHERE _o.ShopName = 'ISAAK'
AND _o.HmerominiaParagelias = '13/12/2018'
ORDER BY _o.Ora DESC;
Rextester Demo (using sample data)
Related
I need to adjust this query to do the search (like) in another column and another table.
See:
$query2 = "
select distinct(lances.codigo)
, datacompra
, horacompra
, cupom
from lances
, ".$tabelaCad."
where lances.idcliente = ".$tabelaCad.".id
and lances.datapgto = '0000-00-00'
and lances.horapgto = '00:00:00'
and (".$tabelaCad.".nome like '%".$cliente."%' or ".$tabelaCad.".usuario like '%".$cliente."%')
group
by lances.codigo
order
by lances.datacompra desc
, lances.horacompra desc
";
He currently searches only on: ".$tabelaCad.".nome and ".$tabelaCad.".usuario.
The variable $tabelaCad is the name of a table called cadastro, and the variable cliente is the one that receives the search POST.
I need her to look too in the column codigo from the table lances and in a new table called registro in the columns reg1 e reg2.
What would the query look like in this case? I have tried several ways and it does not work.
I am working with MySQL 5.7, still...
After a long discussion we found the last relation between the tables.
It is registro.reg1 to lances.codigo.
So the best way to solve the problem is to work with the inncer join.
You save unnecessary typing and can address the tables with aliases which is much more comfortable for writing procedures.
Here is my finished solution:
<?php
$query2 = "
select
distinct lc.codigo as codigo,
lc.datacompra as datacompra,
lc.horacompra as horacompra,
lc.cupom as cupom
from `lances` as lc
inner join `".$tabelaCad."` as ca on lc.idcliente = ca.id
inner join `registr` as ri on lc.codigo = ri.reg1
where lc.idcliente = ca.id
and lc.datapgto = '0000-00-00'
and lc.horapgto = '00:00:00'
and (ca.nome like '%".$cliente."%' or ca.usuario like '%".$cliente."%')
group
by lc.codigo
order
by lc.datacompra desc, lc.horacompra desc
";
?>
I put them in the selection because I do not know exactly what you intend to xD
I connected, I created a quick script in which I want to manage clients, domains and notes.
The problem is that when I add 2 notes to the client from ID: 1 - after viewing I see only one.
The following code shows what I have done so far
SQL Query:
$sql = "SELECT * FROM domain JOIN note ON domain.id = note.domain_id GROUP BY domain.id";
My PHP code:
while($rs = $resultdb->fetch_array(MYSQLI_ASSOC)) {
echo '<tr>';
echo '<td>'.$rs["id"].'</td>';
echo '<td><strong>'.$rs["domain_name"].'</strong></td>';
echo '<td>'.$rs["note"].'</td>';
echo '</tr>';
}
The result he gets is:
ID DOMAIN NOTE
1 "domain1.com" "note 1 to domain1.com"
2 "domain2.com" "note 2 to domain2.com"
However, in the database I have added a few notes to domain1.com.
I would like to see all the notes added to a given domain.
EDIT:
When I do: "SELECT * FROM domain JOIN note ON domain.id = note.domain_id";
I getting:
I getting
I expect
EDIT: Add screnshot
LEFT JOIN
Your GROUP BY is limiting the records retrieved by the query. If you want all of the notes together you can try using GROUP_CONCAT() to produce a single field with all of the notes in one...
$sql = "SELECT domain.id as id, domain.domain_name as domain_name,
GROUP_CONCAT(note.note) as note
FROM domain
LEFT JOIN note ON domain.id = note.domain_id
GROUP BY domain.id";
You might also change the JOIN to LEFT JOIN in case there are no notes for a particular domain.
Probably you need to use a separate query to get "Domain Notes" in the while. for example:
while ($rs = $resultdb->fetch_array(MYSQLI_ASSOC)) {
$sql_notes = "SELECT * FROM notes WHERE domain_id = '" . (int)$rs['domain_id'] . "'";
...
}
you need group_concat group by note.domain_id
if you need exact match the use inner join
"SELECT id, domain, group_concat(note) as note
FROM domain
INNER JOIN note ON domain.id = note.domain_id
GROUP BY note.domain_id";
if you needc result also for id without notes then try
"SELECT id, domain, (group_concat(ifnull(note,'')) as note
FROM domain
LEFT JOIN note ON domain.id = note.domain_id
GROUP BY note.domain_id";
I am requesting your advice about the following:
I have two tables:
Customers and Orders.
I am printing the data of customers inside a table using a while loop:
$sql = "SELECT * FROM wccrm_customers where status = '1' order by date desc";
$result = mysql_query($sql, $db);
while ($daten = mysql_fetch_array($result)) { ?>
echo $daten[id];
echo $daten[name] . ' ' . $daten[vorname];
echo $daten[email];
echo $daten[telefon];
} ?>
Now I try to add a new field in this list: Purchased YES/NO. As we have more customers then buyers, we want to show whether someone has bought or not:
The Connection between this two tables is the first/lastname in both tables!
So if customer.name = orders.name and customer.firstname = orders.firstname I want to echo "YES" if not then "NO"
I tried with a JOIN, but here I just get the results who are in both table:
SELECT *
FROM wccrm_customers AS k
INNER JOIN wccrm_orders AS o
ON o.namee = k.name AND o.firstname = k.firstname
but I need to have all of the customers and the ones who are in both lists marked...
Is this possible? If yes: How can I achieve this?
Thank's for your advice!
Kind regards,
Stefan
This has nothing to do with PHP, or with while loops; you just need to form your join properly:
SELECT DISTINCT
`k`.*,
`o`.`namee` IS NOT NULL AS `Purchased`
FROM `wccrm_customers` AS `k`
LEFT JOIN `wccrm_orders` AS `o`
ON
`o`.`namee` = `k`.`name`
AND `o`.`firstname` = `k`.`firstname`
Read more about the different join types: http://www.sql-join.com/sql-join-types/
(images courtesy of that site, which also contains an example and discussion of almost exactly what you're trying to do!)
By the way, you must have missed the massive red warning banner in the manual about using the deprecated (now removed) mysql_* functions. You should stop doing that! Use MySQLi or PDO instead.
a shorter one
SELECT DISTINCT k.*, IF(o.namee IS NULL, 'no', 'yes') purchased
FROM
wccrm_customers AS k
LEFT JOIN wccrm_orders AS o USING (namee,firstname)
I don't know if these are "complex queries" by defn, but they look very complex to a noob like me.
So I have a query here that will get the latest chart of customer_id=5:
$query = "SELECT c.Chart_ID, c.Chart_Notes
FROM tblchart AS c WHERE c.Customer_ID=5
ORDER BY c.Last_Edited ASC LIMIT 1";
But I have to relate it to another table that uses the Chart_ID as foreign key. How can I get the data from the tblcontent using tblchart.Chart_ID=tblcontent.Chart_ID? I couldn't just add that as:
$query = "SELECT c.Chart_ID, c.Chart_Notes, d.Content_Desc, d.Content_Title
FROM tblchart AS c, tblcontent AS d
WHERE c.Customer_ID=5 AND c.Chart_ID=d.Chart_ID
ORDER BY c.Last_Edited DESC LIMIT 1";
can I? As that would limit the search to just one...the use of LIMIT 1 is just to get the latest, but for the subsequent query (extended query), I am expecting multiple results extracted from tblcontent in addition to the first query I posted. A join, maybe, or union, or a complex query, but how? Please, can anyone help me? Thanks.
SELECT a.Chart_ID, a.Chart_Notes, c.Content_Desc, c.Content_Title
FROM tblChart a
INNER JOIN
(
SELECT Chart_ID, MAX(Last_edited) maxEdited
FROM tblChart
GROUP BY Chart_ID
) b ON a.Chart_ID = b.Chart_ID AND
a.Last_Edited = b.maxEdited
INNER JOIN tblcontent c
ON a.Chart_ID = c.Chart_ID
WHERE a.Customer_ID=5
The following code is used in a query for fetching records. It uses the electors.ID to find the corresponding voting_intention.elector from a second table.
$criteria = "FROM voting_intention,electors WHERE voting_intention.elector = electors.ID AND voting_intention.pledge IN ('C','P') AND electors.postal_vote = 1 AND electors.telephone > 0"
The problem is that some electors will have more than one pledge in the voting_intentions table.
I need it to match only on the latest voting_intention.pledge based on the field votin_intention.date for each elector.
What is the simplest way of implementing that.
The rest of the code:
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria ORDER BY electors.ID ASC"); while($row = mysql_fetch_array($the_elector)) {
echo $row['ID'].','; }
}
You could use a sub-select with the MAX() function. Add the following into your WHERE clause.
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
Here is a SQLFiddle of the results.
So pretty much, you only want to bother looking at the most recent row that fits the first two criteria in your code. In that case, you would want to filter out the voting_intention table beforehand to only have to worry about the most recent entries of each. There's a question/answer that shows how do do that here.
Try selecting the following instead of voting_intention (from the answer of the linked question, some table and field names replaced):
SELECT voting_intention.*
FROM voting_intention
INNER JOIN
(
SELECT elector, MAX(date) AS MaxDate
FROM voting_intention
GROUP BY elector
) groupedintention ON voting_intention.elector = groupedintention.elector
AND voting_intention.date = groupedintention .MaxDate
Question url: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?