MySQL empty rows show up only if table is empty - mysql

I have 2 MySQL tables, one is named _campi (Italian for fields) and one is documenti (Italian for documents).
I need to show all the rows from _campi and where there is a match in documenti this has to show in a field as result.
The weird behavior I cannot understand is that if documentitable is empty I get the expected result (10 rows with many null values, expected result), if documenti IS NOT empty I get only 2 rows as result.
This is the query:
SELECT *, campi_tipologie.valore_campo as tipo_doc FROM _campi as campi_tipologie
LEFT JOIN documenti
ON documenti.doc_type = campi_tipologie.id_campo
WHERE campi_tipologie.categoria = "documenti-immobili"
AND (campi_tipologie.codec = 2 OR campi_tipologie.codec = 0)
AND (documenti.id_immobile IS NULL OR documenti.id_immobile = 422)
ORDER BY id_campo
What am I doing wrong?

SELECT campi
, I
, actually
, want
, c.valore_campo tipo_doc
FROM _campi c
LEFT
JOIN documenti d
ON d.doc_type = c.id_campo
AND d.id_immobile = 422
WHERE c.categoria = "documenti-immobili"
AND c.codec IN(2,0)
AND d.id_immobile IS NULL -- or omit this
ORDER
BY c.id_campo

Related

Mysql filter by multiply ids

I can't finish writing query to filter row by multiply ids. Here is query:
select distinct `storage_file`.*, `storage_tag`.`id` as `tid` from `storage_file`
inner join `storage_file_tag` on `storage_file`.`id` = `storage_file_tag`.`storage_file_id`
inner join `storage_tag` on `storage_tag`.`id` = `storage_file_tag`.`storage_tag_id`
where `storage_file`.`user_id` = 17 and `storage_file`.`deleted_at` is null and
`storage_tag`.`id` IN(13,17);
So the result is without group by statement is:
So.. I need result only with two records which contain tid 13 and 17
And when i replace "IN(13,17)" with storage_tag.id = 13 AND storage_tag.id = 17 - i get no records at all
How can i write subquery which will work like a + b but not a OR b ?
I'm not sure what you do exactly but it seams, that the distinct is not working as you expect, because you select "*" from storage_file, as there are different values in the columns of storage_file, the result is distincted but over all selected columnns and so more the two are selected.
You can replace
... AND id IN (11,22)
with
... AND ( id = 11 OR id = 12)
You need the parentheses because WHERE operator precedence rules are very simple.
Of course,
... AND id = 11 AND id = 12
never returns anything because the id cannot have two different values at the same time.

SQL unwanted results in NOT query

This looks like it should be really easy question, but I've been looking for an answer for the past two days and can't find it. Please help!
I have two tables along the lines of
texts.text_id, texts.other_stuff...
pairs.pair_id, pairs.textA, pairs.textB
The second table defines pairs of entries from the first table.
What I need is the reverse of an ordinary LEFT JOIN query like:
SELECT texts.text_id
FROM texts
LEFT JOIN text_pairs
ON texts.text_id = text_pairs.textA
WHERE text_pairs.textB = 123
ORDER BY texts.text_id
How do I get exclusively the texts that are not paired with A given textB? I've tried
WHERE text_pairs.textB != 123 OR WHERE text_pairs.textB IS NULL
However, this returns all the pairs where textB is not 123. So, in a situation like
textA TextB
1 3
1 4
2 4
if I ask for textB != 3, the query returns 1 and 2. I need something that will just give me 1.
The comparison on the second table goes in the ON clause. Then you add a condition to see if there is no match:
SELECT t.text_id
FROM texts t LEFT JOIN
text_pairs tp
ON t.text_id = tp.textA AND tp.textB = 123
WHERE tp.textB IS NULL
ORDER BY t.text_id ;
This logic is often expressed using NOT EXISTS or NOT IN:
select t.*
from texts t
where not exists (select 1
from text_pairs tp
where t.text_id = tp.textA AND tp.textB = 123
);

filed showing null value when joining table

below is my query
select C.cName,DATE_FORMAT(CT.dTransDate,'%d-%M-%Y') as dTransDate,
(c.nOpBalance+IFNULL(CT.nAmount,0)) AS DrAMount,IFNULL(CTR.nAmount,0) AS
CrAMount,((c.nOpBalance+IFNULL(CT.nAmount,0))-IFNULL(CTR.nAmount,0)) AS
Balance,CT.cTransRefType,CT.cRemarks,cinfo.cCompanyName,cinfo.caddress1,cinfo.cP
honeOffice,cinfo.cMobileNo,cinfo.cEmailID,cinfo.cWebsite from Customer
C LEFT JOIN Client_Transaction CT ON CT.nClientPk = C.nCustomerPk AND
CT.cTransRefType='PAYMENT' AND CT.cClientType='CUSTOMER' AND CT.dTransDate
between '' AND '' LEFT JOIN Client_Transaction CTR ON CTR.nClientPk =
C.nCustomerPk AND CTR.cTransRefType='RECEIPT' AND
CTR.cClientType='CUSTOMER' AND CTR.dTransDate between '2015-05-01' AND
'2015-05-29' LEFT JOIN companyinfo cinfo ON cinfo.cCompanyName like
'%Fal%' Where C.nCustomerPk = 4 Order By dTransDate
it's showing all value but dTransDate ,cTransRefType,cRemarks, showing null.
One obvious thing jumps out at us:
CT.dTransDate BETWEEN '' AND ''
^^ ^^
Another thing that jumps out at us is that there's a semi-Cartesian join between rows from CT and rows from CTR. If 5 rows are returned from CT for a given customer, and 5 rows are returned from CTR, that's going to produce a total of 5*5 = 25 rows. That just doesn't seem like a resultset that you'd really want returned.
Also, if more than one row is returned from cinfo, that's also going to cause another semi-Cartesian join. If there's two rows returned from cinfo, the total number or rows in the resultset will be doubled. It's valid to do that in SQL, but this is an unusual pattern.
The calculation of the balance is also very strange. For each row, the nAmount is added/subtracted from opening balance. On the next row, the same thing, on the original opening balance. There's nothing invalid SQL-wise with doing that, but the result being returned just seems bizarre. (It seems much more likely that you'd want to show a running balance, with each transaction.)
Another thing that jumps out at us is that you are ordering the rows by a string representation of a DATE, with the day as the leading portion. (As long as all the rows have date values in the same year and month, that will probably work, but it just seems bizarre that we wouldn't sort on the DATE value, or a canonical string representation.
I strongly suspect that you want to run a query that's more like this. (This doesn't do a "running balance" calculation. It does return the 'PAYMENT' and 'RECEIPT' rows as individual rows, without producing a semi-Cartesian result.
SELECT c.cName
, DATE_FORMAT(t.dTransDate,'%d-%M-%Y') AS dTransDate
, C.nOpBalance
, IF(t.cTransRefType='PAYMENT',IFNULL(t.nAmount,0),0) AS DrAMount
, IF(t.cTransRefType='RECEIPT',IFNULL(t.nAmount,0),0) AS CrAMount
, t.cTransRefType
, t.cRemarks
, ci.*
FROM Customer c
LEFT
JOIN Client_Transaction t
ON t.nClientPk = c.nCustomerPk
AND t.cClientType = 'CUSTOMER'
AND t.dTransDate >= '2015-05-01'
AND t.dTransDate <= '2015-05-29'
AND t.cTransRefType IN ('PAYMENT','RECEIPT')
CROSS
JOIN ( SELECT cinfo.cCompanyName
, cinfo.caddress1
, cinfo.cPhoneOffice
, cinfo.cMobileNo
, cinfo.cEmailID
, cinfo.cWebsite
FROM companyinfo cinfo
WHERE cinfo.cCompanyName LIKE '%Fal%'
ORDER BY cinfo.cCompanyName
LIMIT 1
) ci
WHERE c.nCustomerPk = 4
ORDER BY t.dTransDate, t.cTransRefTpye, t.id

mySQL: LEFT JOIN where joining needs to be done on different type of data

I have 2 my tables with data and 2 "not mine" tables (in ReferenceDB) where thing ID can be mapped to its name.
One of mine tables is orders with following important columns: charName, stationID, typeID, bid.
Another table has following important columns: transactionDateTime, stationID, typeID, person, transactionType
I started my head braking with idea how to find orders that doesn't have any records for them lately (e.g. given amount of days). But for beginning I set me a task just to find orders that has no records for them at all. For that I figured out LEFT JOIN see biggest query below.
An order for me is a combination of charName/persone + stationID + typeID + transactionType/bid so if actually one of those four changes it is different order then.
Problem is that transactionType can be "yes" or "no" and bid is 0 or not 0. So I cant or DON'T KNOW HOW to JOIN ON different data types. So logically I'd like to join on 4 columns like:
FROM ordersTable LEFT JOIN recordsTable ON ordersTable.typeID = recordsTable.typeID
AND ordersTable.stationID = recordsTable.stationID
AND ordersTable.charName = recordsTable.person
AND ordersTable.bid = recordsTable.transactionType
Clearly last string of above wouldn't work cause of different data types.
So for a moment I thought that I can do such query twice for bid=0 with transactionType="yes" and second time for bid != 0 and transactionType = "no" see my query below for 0/"yes" combination. But seems it doesn't works exactly as I'd like it to. because AND ordersTable.bid IN (0) AND recordsTable.transactionType="yes" in JOIN ON doesn't sem do anything. (As I do get results where bid=1)
SELECT invTypes.typeName, stastations.stationName, main.* FROM referenceDB.invTypes, referenceDB.stastations, (
SELECT ordersTable.charName, ordersTable.stationID, ordersTable.typeID, ordersTable.bid, ordersTable.orderState, ordersTable.volRemaining
FROM ordersTable LEFT JOIN recordsTable ON ordersTable.typeID = recordsTable.typeID
AND ordersTable.stationID = recordsTable.stationID
AND ordersTable.charName = recordsTable.person
AND ordersTable.bid IN (0) AND recordsTable.transactionType="yes"
WHERE recordsTable.typeID IS NULL
AND ordersTable.orderState IN (0) ) as main
WHERE stastations.stationID = main.stationID AND invTypes.typeID = main.typeID;
Questions:
Is it possible to tell mySQL to treat "yes" as 0 or vise versa? If yes how do I do it in my query? If no what would be my work around (to find orders that doesn't have records related to them)?
And possibly some one can suggset a query that will find orders that didn't have records within given amount of days?
Thank you in advance!
One way is to use the explicit comparisons:
((ordersTable.bid = 0 and recordsTable.transactionType = 'No') or
(ordersTable.bid = 1 and recordsTable.transactionType = 'Yes')
)
Another would be to use a case statement:
(case when recordsTable.transactionType = 'No' then 0 else 1 end) = ordersTable.bid
SELECT invTypes.typeName, stastations.stationName, main.* FROM referenceDB.invTypes, referenceDB.stastations, (
SELECT ordersTable.charName, ordersTable.stationID, ordersTable.typeID, ordersTable.bid, ordersTable.orderState, ordersTable.volRemaining
FROM ordersTable LEFT JOIN recordsTable ON ordersTable.typeID = recordsTable.typeID
AND ordersTable.stationID = recordsTable.stationID
AND ordersTable.charName = recordsTable.person
AND ((ordersTable.bid = 0 AND recordsTable.transactionType = 'yes') OR
(ordersTable.bid != 0 AND recordsTable.transactionType = 'no'))
WHERE recordsTable.typeID IS NULL
AND ordersTable.orderState IN (0) ) as main
WHERE stastations.stationID = main.stationID AND invTypes.typeID = main.typeID;

Mysql Query to retrieve Values using if statement

select
IFNULL(sum(invoice0_.INV_AMT),0) as col_0_0_,IFNULL(sum(invoice1_.INV_AMT),0) as col_0_0_
from
hrmanager.invoice invoice0_,
hrmanager.invoice invoice1_
where
invoice0_.FROM_LEDGER=1
**or** invoice1_.TO_LEDGER=1
and (
invoice0_.INV_DATE between '1900-12-20' and '2012-01-30'
)
and invoice0_.ACTIVE='Y'
and invoice0_.COMP_ID=2
and invoice1_.COMP_ID=2
and invoice0_.INV_TYPE='CLIENT'
and invoice1_.INV_TYPE='CLIENT';
Here i wish to select the sum of amount of all from_ledger =1 and next column should display the sum of amount of all to_ledger=1 but here gave and/or in the condition retrieve the same data,In Db here from ledger=1 then the result is 7000 and toledger=1 then it will 0 but the above query retrieve the two columns are same value like 0 or 7000
It looks like your query is a bit of a mess. You are doing a query from the same table twice, but no JOIN condition which will result in a Cartesian result. I THINK what you are looking for is that your table "Invoice" has two columns in it... "To_Ledger" and "From_Ledger", the "INV_AMT", and some other fields for criteria... This should get you closer to your answer.
select
sum( if( inv.From_Ledger = 1, inv.Inv_Amt, 0 )) as FromInvoiceAmounts,
sum( if( inv.To_Ledger = 1, inv.Inv_Amt, 0 )) as ToInvoiceAmounts
from
hrmanager.invoice inv
where
1 in ( inv.From_Ledger, inv.To_Ledger )
AND inv.inv_date between '1900-12-20' and '2012-01-30'
and inv.Active = 'Y'
and inv.Comp_ID = 2
and inv.Inv_Type = 'CLIENT'