I’ve been having problems trying to retrieve data from my database to a DataTable in Microsoft Visual C#. I’ve been told it’s because of improper use of INNER JOINs. The query (Fill method) is the one that follows.
SELECT Bordero.id AS id, Titulo.id AS id_titulo, Titulo.valor AS valor_titulo,
Sacado.nome AS nome_sacado, Cliente.nome AS nome_cliente, Sacado.documento,
Titulo.taxa_adm AS taxa_adm_titulo, Titulo.desagio AS desagio_titulo,
Titulo.liquido AS liquido_titulo,
(CASE Titulo.tipo
WHEN 'True' THEN 'Cheque'
ELSE 'Duplicata'
END) AS tipo, Titulo.dias, Titulo.codigo, Titulo.vencimento,
Titulo.data_base, Bordero.desagio AS desagio_bordero,
Bordero.taxa_adm AS taxa_adm_bordero, Bordero.liquido AS liquido_bordero,
Bordero.bruto, Bordero.duplicata, Bordero.desconto, Bordero.iss, Bordero.iof,
Bordero.cpmf, Bordero.pis, Bordero.cofins, Desconto.valor AS valor_desconto,
Desconto.descricao, Bordero.id_cliente
FROM Bordero
INNER JOIN Cliente ON Bordero.id_cliente = Cliente.id
INNER JOIN Titulo ON Bordero.id = Titulo.bordero_id
INNER JOIN Sacado ON Sacado.id = Titulo.sacado_id
INNER JOIN Desconto ON Cliente.id = Desconto.id_cliente
The database diagram looks like this:
http://i53.tinypic.com/t0g4qp.jpg
Any hints on what’s wrong?
Without stating what your problem is that you’re experiencing my guess would be that you may need to be using
LEFT OUTER JOINfor some of the tables instead of allINNER JOIN.When using an
INNER JOINin a query, the data that you’re matching via theONclause must be not null in both tables. Meaning that if the ID exists on the left table (the one in theFROMclause) there must be a matching record in the right table (the one you’re joining in via theINNER JOIN). If the right table does not have a matching record, the entire result is dropped from the query.By using a
LEFT OUTER JOINinstead, you allow the right table to returnNULLinstead for each data row that doesn’t match.Using the above tables, if you were to do an
FROM A INNER JOIN B ON A.ID = B.IDonly rows 1 and 3 would be returned. If you were to do aFROM A LEFT OUTER JOIN B ON A.ID = B.IDall rows fromAwould be returned andB.Addresswould be null for #2.