MySQL搜索跨越三个表连接

时间:2012-10-11 15:23:05

标签: mysql whmcs

我在MySQL数据库中有以下三个表,结构如下:

tblinvoices

userid | id |税收|日期

tblinvoiceitems

userid | RELID

tblcustomfieldvalues

relid |价值| fieldid

我要做的是查找在特定日期范围内且税率为0的所有发票编号(tblinvoices.id),并且其fieldid为5,其值包含字母。

这是我用代码尝试实现这一目标的程度,遗憾的是它不起作用,我无法理解为什么。我知道这是相当复杂的,所以任何建议都表示感谢,我不确定我的方法是否正确。

SELECT DISTINCT id, date  
FROM `tblinvoices`  
INNER JOIN (SELECT userid,tblinvoiceitems.relid  
FROM  `tblinvoiceitems`  
INNER JOIN `tblcustomfieldsvalues`  
ON tblinvoiceitems.relid=tblcustomfieldsvalues.relid  
WHERE  `fieldid` =5  
AND  `value`   
REGEXP  '[A-Za-z]') tbl  
ON tblinvoices.userid=tbl.userid  
WHERE `taxrate` = 0  
AND `date`  
BETWEEN  '2012-07-01' AND '2012-09-31'  

简化但结果仍不正确:

SELECT DISTINCT i.id, i.date  
FROM `tblinvoices` i
INNER JOIN `tblinvoiceitems`  it ON it.userid=i.userid
INNER JOIN `tblcustomfieldsvalues`  cf ON it.relid=cf.relid  
WHERE  cf.`fieldid` =5  
AND  cf.`value` REGEXP  '[A-Za-z]'
AND i.`taxrate` = 0  
AND i.`date`  BETWEEN  '2012-07-01' AND '2012-09-31'  
GROUP BY i.id

1 个答案:

答案 0 :(得分:2)

我只是在简化你的查询。试试这个

SELECT i.id, i.date  
FROM `tblinvoices` i
INNER JOIN `tblinvoiceitems`  it ON it.userid=i.userid
INNER JOIN `tblcustomfieldsvalues`  cf ON it.relid=cf.relid  
WHERE  cf.`fieldid` =5  
AND i.`taxrate` = 0  
AND i.`date`  BETWEEN  '2012-07-01' AND '2012-09-31'  
GROUP BY i.id

希望这会起作用