I have been getting duplicate value from my inner join table - php

enter image description hereI have been using this sql code on my php. However, for every product i have been getting twice of them or a duplicate of them. How should i write to make it do not duplicate the product i get and just get once?
<?php
include ('classes/functions.php');
if(isset($_POST['user_id'])){
$user_id = $_POST['user_id'];
$check_receipt = "select si.shipping_name,
si.shipping_address,
si.shipping_contact,
si.shipping_email,
o.order_date,
o.trx_id,
o.tracking_num,
o.quantity,
o.store_id,
o.product_id,
p.product_title,
p.product_price,
p.product_img1,
p.product_weight
from shipping_infos si
inner join orders o
on si.user_id = o.user_id
inner join products p
on p.product_id = o.product_id
where si.user_id='".$user_id."' order by o.trx_id;" ;
$run_receipt_checking = mysqli_query($con, $check_receipt);
$result = array();
while($row = mysqli_fetch_array($run_receipt_checking)){
array_push($result,
array(
'shipping_name'=>$row[0],
'shipping_address'=>$row[1],
'shipping_contact'=>$row[2],
'shipping_email'=>$row[3],
'order_date'=>$row[4],
'trx_id'=>$row[5],
'tracking_num'=>$row[6],
'quantity'=>$row[7],
'store_id'=>$row[8],
'product_id'=>$row[9],
'product_title'=>$row[10],
'product_price'=>$row[11],
'product_img1'=>$row[12],
'product_weight'=>$row[13]
));
}
echo json_encode(array("result"=>$result));
}
?>

Duplicates in the result set imply multiple matches in the joins. Without sample data, it is really hard to tell where it is occurring.
If I had to guess based on the query, then would guess that users could have multiple rows in shipping_infos. There are definitely other possibilities, but I would start with a simple query and build up to the final query.

I'm guessing your p.product_id is an unique field in your DB.
If so you could add GROUP BY p.product_id at the end of your statement.
$check_receipt = "select si.shipping_name,
si.shipping_address,
si.shipping_contact,
si.shipping_email,
o.order_date,
o.trx_id,
o.tracking_num,
o.quantity,
o.store_id,
o.product_id,
p.product_title,
p.product_price,
p.product_img1,
p.product_weight
from shipping_infos si
inner join orders o
on si.user_id = o.user_id
inner join products p
on p.product_id = o.product_id
where si.user_id='".$user_id."' order by o.trx_id group by p.product_id;" ;

Related

Using OR, AND operator in single query

I am trying to list the records which meets my condition. As ii am using AND and OR operator together i am not getting the exact report. Here is my query
SELECT o.sales_order_id AS SID, o.reference, o.status, o.last_modified, sol.sales_order_id, sol.item, sol.quantity, sol.selling_price, sol.discount, sol.tax, SUM(sol.tax_amount) AS Tamt, SUM(sol.total) as Total, i.iid, GROUP_CONCAT(DISTINCT i.name) AS iname, l.company, t.tax_id, t.name as tname, t.rate from orders o INNER JOIN before_order_line_items sol ON o.sales_order_id = sol.sales_order_id INNER JOIN leads l ON o.company_id=l.id INNER JOIN items i ON sol.item=i.iid INNER JOIN taxes t ON sol.tax=t.tax_id WHERE o.order_quote='Order' AND o.authorise='Yes' OR o.assigned_to=6 OR o.user_id=6 GROUP BY o.sales_order_id ORDER BY o.sales_order_id DESC
I am storing both orders and quotations in single table Orders, for orders i store it as Order in order_quote column, for Quotations it is Quote
It is not checking order_quote='Order' condition, it displays both orders and quotations.
if i remove OR o.assigned_to=6 OR o.user_id=6 , it gives proper result.
I tried using DISTINCT like this
SELECT DISTINCT o.order_quote=`Order`, .....
But does't work.
UPDATED
SELECT o.sales_order_id AS SID, o.reference, o.status, o.last_modified, sol.sales_order_id, sol.item, sol.quantity, sol.selling_price, sol.discount, sol.tax, SUM(sol.tax_amount) AS Tamt, SUM(sol.total) as Total, i.iid, GROUP_CONCAT(DISTINCT i.name) AS iname, l.company, t.tax_id, t.name as tname, t.rate from orders o INNER JOIN before_order_line_items sol ON o.sales_order_id = sol.sales_order_id INNER JOIN leads l ON o.company_id=l.id INNER JOIN items i ON sol.item=i.iid INNER JOIN taxes t ON sol.tax=t.tax_id WHERE (o.order_quote='Order' AND o.authorise='Yes') AND (o.assigned_to=6 OR o.user_id=6) GROUP BY o.sales_order_id ORDER BY o.sales_order_id DESC
You need to use parentheses. I'm not sure exactly how, but your current where clause is interpreted as:
WHERE (o.order_quote = 'Order' AND o.authorise = 'Yes') OR
(o.assigned_to = 6) OR
(o.user_id = 6)
I would guess that you want something like this:
WHERE (o.order_quote = 'Order' AND o.authorise = 'Yes') AND
(o.assigned_to = 6 OR o.user_id = 6)
But that is mere speculation.
Or perhaps:
WHERE (o.order_quote = 'Order' AND
(o.authorise = 'Yes' OR o.assigned_to = 6 OR o.user_id = 6)

Select Mysql Query inside echo of another query

Hello I would like to know how I can realizes query selection inside echo of already processed query.
This is my firs Mysql Query
SELECT * FROM cursos_modulos
foreach($result as $row)
{
$id = $row['id'];
echo"
Here where the echo goes I have to make the other query which is:
SELECT COUNT(users.userID)
FROM users
INNER JOIN subscriptions
ON users.userID = subscriptions.user_id
WHERE subscriptions.curso_id = $id
and at the end to put the result of this query
foreach($result as $rowc)
.$rowc[0]."};
Any help how I can achive this goal will be very welcome. Question is simple. First Select Selects the Cours with it's unique ID. which ID have to be used in the second, third and else... queries. Which queries are like the second one. So First Select Course and then Select different parameters from this course based on this ID. at the end dump results of each of the selections with different indications"
Do it all in one query:
SELECT c.*, count(s.curso_id) as count
FROM cursos_modulos AS c
LEFT JOIN subscriptions AS s ON s.curso_id = c.id
LEFT JOIN users AS u ON u.userID = s.user_id
The LEFT JOIN is needed to get 0 for the count if there are no matching rows in subscriptions.
To include a second count of approved subscriptions:
SELECT c.*, count(s.curso_id) as count, SUM(IF(s.approved = 'approved', 1, 0)) AS count_approved
FROM cursos_modulos AS c
LEFT JOIN subscriptions AS s ON s.curso_id = c.id
LEFT JOIN users AS u ON u.userID = s.user_id

nested queries and calculations all in the same query - is it possible?

I am running a MySQL query to get all "users" with current orders.
(It is possible for a user to have more than 1 associated orders in the db/query).
However i also want to get the total order value for each user and total order count for each user that is being returned (within the below query).
I could do these calculations in PHP, but feel it is possible and would be neater all done within the same SQL query (if possible).
This is the basic query with no attempt to make the above calculations
SELECT u.UserID, u.UserName,
o.OrdersID, o.OrderProductName, o.OrderProductQT, o.OrderTotalPrice, o.tUsers_UserID, o.tOrderStatus_StatusID, o.OrderDate, o.OrderDateModified, o.OrderVoid, o.tProducts_ProductID,
os.OrderStatusName,
ud.UserDetailsName, ud.UserDetailsPostCode,
p.ProductName, p.ProductImage1
FROM tusers u
INNER JOIN torders o ON o.tUsers_UserID = u.UserID
INNER JOIN torderstatus os ON os.OrderStatus_StatusID = o.tOrderStatus_StatusID
INNER JOIN tuserdetails ud ON ud.tUsers_UserID = u.UserID
LEFT JOIN tproducts p ON p.ProductID = o.tProducts_ProductID
WHERE o.tOrderStatus_StatusID = ?
GROUP BY u.UserID
ORDER BY OrdersID DESC
I have tried various nested select queries, but none of them work (right)
Is what i want to do possible in SQL or should i just do it all in PHP once i have the returned query results?
Any advice is much appreciated
You can embed the slightly modified queries into another query. For instance:
SELECT userid, SUM(orderid) FROM orders GROUP BY userid
and
SELECT userid, SUM(distinct productid)
FROM
orders o
INNER JOIN orderlines ol on ol.orderid = o.orderid
GROUP BY
userid
can be combined to:
SELECT
u.userid
u.fullname,
(SELECT SUM(orderid)
FROM orders o
WHERE o.userid = u.userid) as ORDERCOUNT,
(SELECT SUM(distinct productid)
FROM
orders o
INNER JOIN orderlines ol on ol.orderid = o.orderid
WHERE
o.userid = u.userid) as UNIQUEPRODUCTS
FROM
users u
Note that the latter query will return all users and will return NULL for ORDERCOUNT or UNIQUEPRODUCTS when the subquery doesn't return anything (when a user doesn't have orders). Also, the query will fail when a subquery returns more than 1 row, which should never happen in the example I posted.

Using PHP in smarty template system to get SUM from database

Here is the code I'm currently using:
$result = mysql_query("
SELECT SUM(s.amount)
FROM tblaffiliatespending s
JOIN tblaffiliatesaccounts a
ON a.id=s.affaccid
JOIN tblhosting h
ON h.id = a.relid
JOIN tblproducts p
ON p.id = h.packageid
JOIN tblclients c
ON c.id = h.userid
WHERE affiliateid = $affiliateid
ORDER
BY clearingdate DESC;
");
$data = mysql_fetch_array($result);
$pendingcommissions = $data['?????????'];
$this->assign("pendingamount", $pendingcommissions);
What I'm not sure about is what to enter for ????????? on the third line. I've tried all of these things and none of them have worked:
$pendingcommissions = $data['SUM(tblaffiliatespending.amount)'];
$pendingcommissions = $data['SUM'];
$pendingcommissions = $data['tblaffiliatespending.amount'];
$pendingcommissions = $data['tblaffiliatespending'];
$pendingcommissions = $data['amount'];
Any ideas on what this needs to be changed to?
You need to give the alias for the sum of amount SUM(s.amount) total_amountso when you execute query and fetch the results from it you will have the sum of your amount column on total_amount index in resultant array and you can access it by $data['total_amount'];, also note using aggregate functions without grouping then will result in a single row not per group
SELECT SUM(s.amount) total_amount
FROM tblaffiliatespending s
JOIN tblaffiliatesaccounts a
ON a.id=s.affaccid
JOIN tblhosting h
ON h.id = a.relid
JOIN tblproducts p
ON p.id = h.packageid
JOIN tblclients c
ON c.id = h.userid
WHERE affiliateid = $affiliateid
ORDER
BY clearingdate DESC

How to select the data from a table when it's ability is in an other table?

I have 3 tables:
-Sales
-Items_cstm
-Items
Sales and Items_cstm contains the data I have to get with the query and Items the ability of the item "Deleted (1 or 0)" (and dome more info I don't need).
The Items_cstm's id is = Items's id.
I have to list the Sales of the Items which aren't deleted (0).
I've tried somehow with inner join but it didn't work and I don't really know what am I doing wrong:
SELECT Items_cstm.quantity
FROM Items_cstm, Sales
WHERE '".$_POST['name']."' = Sales.name
AND
INNER JOIN Items ON Items_cstm.id = Items.id
WHERE Items.deleted = 0;
You can join your tables like this (but you did not show the link between Items_cstm and sales - you have to modify that)
SELECT ic.quantity
FROM Items_cstm ic
INNER JOIN Sales s on s.id = ic.id
INNER JOIN Items i ON ic.id = i.id
WHERE i.deleted = 0
AND s.name = '".$escapedName."'
Also always escape your user input.
Try something like this:
SELECT Items_cstm.quantity
FROM Items_cstm
INNER JOIN Sales ON sales.JOINCOLUMN = Items_cstm.JOINCOLUMN
INNER JOIN Items ON Items_cstm.id = Items.id
WHERE Sales.name = '".$_POST['name']."'
WHERE Items.deleted = 0;
Replace JOINCOLUMN above with the columns that let you match records between these two tables
Something like this should work:
SELECT Items_cstm.quantity
FROM Items_cstm
INNER JOIN Items ON Items_cstm.id = Items.id
INNER JOIN Sales ON Items_cstm.id = Sales.item_id // ??? check this one for column names
WHERE '$name' = Sales.name AND Items.deleted = 0;
Beware of SQL injection.

Categories