This is my php script that selects everything from invoiceNo where invoiceNo is distinct.
<?php
require 'init.php';
$query = 'SELECT * FROM `selected_items` WHERE invoiceNo IN ( SELECT DISTINCT ( invoiceNo) AS invoiceNo FROM selected_items ) GROUP BY invoiceNo;';
$res = mysqli_query($con, $query);
$result = [];
while ($row = mysqli_fetch_array($res)) {
array_push($result, [
'custInfo' => $row[0],
'invoiceNo' => $row[1],
'barcode' => $row[2],
'description' => $row[3],
'weight' => $row[4],
'rate' => $row[5],
'makingAmt' => $row[6],
'net_rate' => $row[7],
'itemTotal' => $row[8],
'vat' => $row[9],
'sum_total' => $row[10],
'bill_type' => $row[11],
'date' => $row[12],
'advance' => $row[13],
'balance' => $row[14],
]);
}
echo json_encode(['result' => $result]);
mysqli_close($con);
Right now this script gives me the first value from sum_total i.e it gives me the first row from my database how can I get the last row.I am new to programming any suggestions or help is appreciated.Thanks :)
Select * From (
SELECT t.*,
#rownum := #rownum + 1 AS rank
FROM selected_items t,
(SELECT #rownum := 0) r order by rank DESC
) si GROUP BY si.invoiceNo;
This query solved my problem
Try this, i think this is you want, may it help
$query ="SELECT max( `sum_total` ) FROM `selected_items` GROUP BY invoiceNo;";
try like this :
$query ="SELECT * FROM `selected_items` WHERE invoiceNo IN ( SELECT DISTINCT ( invoiceNo) AS invoiceNo FROM selected_items ) ORDER BY `sum_total` DESC";
$query ="SELECT max( `sum_total` ) FROM selected_items";
Where column_name can be vary.
If you need to get only last record use limit.
$query ="SELECT * FROM `selected_items` GROUP BY invoiceNo ORDER BY `sum_total` DESC limit 1;
If you need to get highest to lowest sum_total record try the below code,
$query ="SELECT * FROM `selected_items` where `sum_total` = (SELECT max( `sum_total` ) FROM `selected_items` GROUP BY invoiceNo) GROUP BY invoiceNo ORDER BY `sum_total` DESC;
Related
I'm trying to write one query for joining 3 tables without link, I was trying with UNION SQL command like this:
SELECT *
FROM
(SELECT
a.id AS field_aa, a.column2 AS field_ab, a.column3 AS field_ac
FROM tableA a
UNION
SELECT
b.id AS field_ba, b.column2 AS field_bb, b.column3 AS field_bc
FROM tableB b
UNION
SELECT
c.id AS field_ca, c.column2 AS field_cb, c.column3 AS field_cc
FROM tableC c) abc
WHERE 1;
And after i want to fill 3 arrays for each table
while( ($arr = $_opDB->fetch_assoc($result)) != FALSE ) {
$array_one = array(
'field_id' => $arr['field_aa'],
'field_one' => $arr['field_ab'],
'field_two' => $arr['field_ac'],
) ;
$array_two = array(
'field_id' => $arr['field_ba'],
'field_one' => $arr['field_bb'],
'field_two' => $arr['field_bc'],
) ;
$row_three = array(
...
) ;
$global_array['firstSelect'][] = $array_one ;
$global_array['secondSelect'][] = $array_two ;
$global_array['thirdSelect'][] = $array_three ;
}
All my entries are added in $global_array['firstSelect'], others are empty
You could add a field indicating from which table a row is coming:
SELECT a.id AS field_id,
a.column2 AS field_2,
a.column3 AS field_3,
'firstSelect' as select_name
FROM tableA a
UNION
SELECT b.id AS field_id,
b.column2 AS field_2,
b.column3 AS field_3,
'secondSelect' as select_name
FROM tableB b
UNION
SELECT c.id AS field_id,
c.column2 AS field_2,
c.column3 AS field_3,
'thirdSelect' as select_name
FROM tableC c
And here is the PHP to process the result:
while(($row = $_opDB->fetch_assoc($result)) {
$select = $row['select_name'];
$global_array[$select][] = ['field_id' => $row['field_id'],
'field_one' => $row['field_2'],
'field_two' => $row['field_3']];
}
As CBroe rightly commented: If the tables are indeed identical you should make them into one table.
I need to extract 3 result from each category in a database using cakephp, I tried to query in database using mysql session variable and conditions as below
SELECT *, #question_cat_rank := 0, #question_cat_country:=''
FROM
(SELECT *,
#question_cat_rank := IF(#question_cat_country = question_setname.question_cat, #question_cat_rank + 1, 1) AS question_cat_rank,
#question_cat_country := question_cat
FROM question_setname
ORDER BY question_cat desc
) ranked
WHERE question_cat_rank <= 3
its working fine in mysql query analyzer but when i query using cakephp its returning all results in table instaed of 3 results
i tried to create it using cakephp way like below
public $virtualFields = array(
'#catvirt' => 1,
'#catvirt2' => 'question_cat',
'incrmt' => 'IF(#catvirt2 = question_cat, #catvirt+1, 1)',
);
function getquestionGroup(){
$result1 = $this->find('all', array(
'fields' => array('question_cat', '#catvirt2', 'incrmt'),
'#catvirt2'=> 'question_cat',
'#catvirt' => '#catvirt'
)
);
$result = $this->find('all', array($result1,
'conditions' => array('#catvirt <=' => 3),
)
);
i tried to execute as prepared statementand stored procedure also still no luck its returning all results
any help will be appreciated
I would write that query this way:
SELECT x.*
FROM
( SELECT *
, #question_cat_rank := IF(#question_cat_country = question_cat, #question_cat_rank + 1, 1) question_cat_rank
, #question_cat_country := question_cat
FROM question_setname
, (SELECT #question_cat_rank := 0, #question_cat_country:='') vars
ORDER
BY question_cat DESC
) x
WHERE question_cat_rank <= 3;
UPDATE:
I used the following query:
$act1 = $dbh->prepare("(SELECT Title, start_date FROM service_o ORDER BY start_date DESC limit 2) UNION (SELECT Title, Start_Date FROM research_o ORDER BY start_date DESC limit 2) UNION (SELECT Title, Start_Date FROM intern_o ORDER BY start_date DESC limit 2) UNION (SELECT Title, Start_Date FROM participate_o ORDER BY start_date DESC limit 2)");
$act1->execute();
$act1->fetchAll();
$result = $act1->fetchall(PDO::FETCH_ASSOC);
Is it absolutely necessary to use var_dump? Moreover, I get an undefined offset error on using this:
echo $result[0]['Title']
Use execute, then fetchAll to return all your results as an array.
$act1 = $dbh->prepare("SELECT Title, start_date FROM table1 ORDER BY start_date DESC limit 2
UNION
SELECT Title, Start_Date FROM research_o ORDER BY table2 DESC limit 2
UNION
SELECT Title, Start_Date FROM intern_o ORDER BY table3 DESC limit 2
UNION
SELECT Title, Start_Date FROM participate_o ORDER BY table4 DESC limit 2 ");
$act1->execute();
$result = $act1->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
Your array will be in a structure that looks like this:
$result = [
'0' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'1' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'2' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'3' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'4' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'5' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'6' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
'7' => [ 'Title' => 'some title', 'Start_Date' => '2009-10-15'],
];
This means you could access each element of the array in your panels by calling:
echo $result[0]['Title'] . ' - ' . $result[0]['Start_Date'];
Or if you want to loop through them and display all at once:
foreach ($result as $row) {
echo '<div class="panel">' . $row['Title'] . ' - ' . $row['Start_Date'] . '</div>';
}
Read more on execute here which shows to fetch data from a query: http://php.net/manual/en/mysqli-stmt.execute.php
Executes a query that has been previously prepared using the mysqli_prepare() function.
I have a SQL query that has alias in it. The problem is, when I try to get the values of columns it doesn't show the correct values:
$sql = "SELECT p.ID, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";
$result = array();
$i = 0;
foreach ($this->dbconnect->query($sql) as $row)
{
$result[$i] = array(
'ID' => $row['p.ID'],
'ProfileID' => $row['p.ProfileID'],
'ModuleID' => $row['p.ModuleID'],
'View' => $row['p.View'],
'Add' => $row['p.Add'],
'Edit' => $row['p.Edit'],
'Delete' => $row['p.Delete']);
$i += 1;
}
Running shows no value when in the database it's actually 10.
If I change the above code to the following:
$sql = "SELECT p.ID, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";
$result = array();
$i = 0;
foreach ($this->dbconnect->query($sql) as $row)
{
$result[$i] = array(
'ID' => $row['ID'],
'ProfileID' => $row['ProfileID'],
'ModuleID' => $row['ModuleID'],
'View' => $row['View'],
'Add' => $row['Add'],
'Edit' => $row['Edit'],
'Delete' => $row['Delete']);
$i += 1;
}
Miraculously, running shows the value of m.ID instead of p.ID. It is strange why the first example is incorrect. Am I missing something here?
You should something like this...
SELECT p.ID as p_ID, ...
And
'ID' => $row['p_ID'],
Use aliases in SELECT to each column, which are same:
$sql = "SELECT p.ID AS permission_id, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID AS module_id FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";
then:
foreach(...)
{
$result[$i] = array(
'Perm_ID' => $row['permission_id'],
'Module_ID' => $row['module_id'],
...
}
I'm trying to use Group by in find method for my relational database I want to get the latest record with unique receiver_id out of result set filtered by user_id and below is my code:
$this->loadModel('Chat');
$lastChat = $this->Chat->find('all', array(
'conditions' => array(
'Chat.user_id' => $user_id['User']['id']
),
'fields' => array(
'Chat.id',
'Chat.chat',
'Chat.user_id',
'Chat.receiver_id',
'Chat.read',
'Chat.created'
),
'group' => array('Chat.receiver_id'),
'order' => array('Chat.created DESC')
));
However, this does not seem to work. I'm not sure why but I'm only getting one result...
How can I get multiple results with rules based on above.
Try the following:
$db = $this->Chat->getDataSource();
$chats = $db->query("SELECT * , (Chat.user_id + Chat.receiver_id) AS dist
FROM (
SELECT *
FROM chats t
WHERE ( t.user_id =$id OR t.receiver_id =$id )
ORDER BY t.id DESC
) Chat
GROUP BY dist
ORDER BY Chat.id DESC");