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 im开发者_运维知识库proper 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 JOIN
for some of the tables instead of all INNER JOIN
.
When using an INNER JOIN
in a query, the data that you're matching via the ON
clause must be not null in both tables. Meaning that if the ID exists on the left table (the one in the FROM
clause) there must be a matching record in the right table (the one you're joining in via the INNER JOIN
). If the right table does not have a matching record, the entire result is dropped from the query.
By using a LEFT OUTER JOIN
instead, you allow the right table to return NULL
instead for each data row that doesn't match.
TABLE A TABLE B
ID | Name ID | Address
1 | Alice 1 | 123 ABC St.
2 | Bob 3 | 789 XYZ St.
3 | Cam
Using the above tables, if you were to do an FROM A INNER JOIN B ON A.ID = B.ID
only rows 1 and 3 would be returned. If you were to do a FROM A LEFT OUTER JOIN B ON A.ID = B.ID
all rows from A
would be returned and B.Address
would be null for #2.
精彩评论