问题
I'm using mysql/php/apache. I have the following situation:
2 tables where I need to compare some information, it is no problem if I use INNER JOIN, but I have a problem in my columns.
table 1 -> invoices_account
table 2 -> invoices_payable
on my invoices_account I have this fields: id, categ, categ_name, code, name, active, essential
on my invoices_payable I have: id, ..(all my fields).. , reference
the value of my field reference in invoices_payable is the same value of categ and code in the other table invoices_account. It was concatenated in a one field only.
Now I need to report only the essential accounts and I have no idea how to SELECT 2 fields from one table and compare it on 1 field of the another table.
I hope to be clear in my explanation.. but it is a kind of situation that was not planned on that project. Now I can't modify the structure of my database 'cause I have tons of data inside.
Does somebody have any idea how to solve this hot trouble? Very Thanks for anyone.
My old query was something like this, but not working cause the field categ and code need to be concatenated to be compared with referencia.
SELECT SUM(ip.total) as total, ip.due_date, ip.status, ip.referencia
FROM invoices_payable ip
INNER JOIN invoices_account ON ip.referencia = invoices_account.code
WHERE due_date BETWEEN '$dinov' and '$dfnov'
AND invoices_payable.referencia = invoices_account.code
AND invoices_payable.status ='paid'
AND invoices_account.essential = 1
- WHERE $dinov, $dfnov is my date.
回答1:
SELECT categ_name, ... FROM invoices_account
JOIN invoices_payable
ON CONCAT(invoices_account.categ, invoices_account.code) = invoices_payable.reference
回答2:
You can use the CONCAT() function in your join's ON clause.
It might be very slow since it won't be able to use an index on the invoices_account_table, but funcitonally you should be able to use a query like this:
select ...
from invoices_account
inner join invoices_payable
on invoices_payable.reference = concat(invoices_payable.categ,invoices_payable.code);
回答3:
Another question answered. Thanks.
in the end my query look like this
$sql = "SELECT SUM(invoices_payable.total) as total, invoices_payable.due_date, invoices_payable.status, invoices_payable.referencia, invoices_payable.status, invoices_account.essential \n"
. "FROM invoices_account \n"
. "INNER JOIN invoices_payable \n"
. "ON invoices_payable.referencia = concat(invoices_account.categ,invoices_account.code) \n"
. "WHERE due_date BETWEEN \'2010-11-01\' and \'2010-12-01\' \n"
. "AND invoices_payable.status =\'paid\' \n"
. "AND invoices_account.essential = 1";
来源:https://stackoverflow.com/questions/4512491/how-to-select-2-fields-from-one-table-and-compare-it-on-1-field-of-the-another-t