I have two tables sale and receipt ,table structure is give below.
sale table
id total sale_type cust_id
1 100 credit 10
2 200 payment 9
receipt
id net_mount payment_type cust_id
1 50 CDM 10
2 150 Hand Over 9
My problem is when i give sale_type in where condition i got matched data from sale table and also the data from receipt table, when sale_type is give i want only the matched value of sale table . same situation in the case of payment_type.
Code
<?php
$where='where 1';
$where2='where 1';
if($sale_type<>'')
{
$where.=" and sale.sale_type='$sale_type'";
}
if($deposited_type<>'')
{
$where2.=" and receipt.deposited_type='$deposited_type'";
}
if($cust_name<>'' || $cust_id<>'')
{
$where.=" and (sale.cust_id='$cust_name' or sale.cust_id='$cust_id')";
$where2.=" and (receipt.cust_id='$cust_name'
or receipt.cust_id='$cust_id')";
}
select total, net_amount from (select total, null as net_amount,
2 as sort_col from sale $where union
all select
null as total, net_amount, 1 as sort_col from receipt $where2)
as a order by sort_col desc
?>
Any body give any solution for these issue?
The FROM
part of your query has to be parametrized in function of the tables you need. You have to do something like this:
<?php
$where='where 1';
$where2='where 1';
if ($sale_type<>'' && $deposited_type<>'') {
$where.=" and sale.sale_type='$sale_type'";
$where2.=" and receipt.deposited_type='$deposited_type'";
$tables = "sales INNER JOIN receipt ON sales.cust_id. = receipt.cust_id"
}
else if($sale_type<>'') {
$where.=" and sale.sale_type='$sale_type'";
$tables = "sales"
}
else if($deposited_type<>'') {
$where2.=" and receipt.deposited_type='$deposited_type'";
$tables = "receipt"
}
and then you build your query with:
SELECT ...
FROM $tables
WHERE conditions with $where and $where2
Beware of SQL injections with conditions like receipt.deposited_type='$deposited_type'
I think your database structure is wrong, if the customer made a more than one sale the query will generate a duplicate result
Please create a database structure like below
sale(id,total,sale_type,cust_id)
receipt(id,net_mount,payment_type,sale_id)
In the above table you can put sale_id in receipt table instead of cust_id
so the query will be
select sale.total,receipt.net_amount,receipt.payment_type from sale INNER JOIN
receipt ON sale.id=receipt.sale_id where sale.sale_type='credit'
You can easily generate above query in php. Please let me for further clarification.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.