[英]SQL SELECT and join multiple tables erron in query?
我有这个查询按预期工作:
$sql = '
SELECT s.rowid
, f.fk_soc
, s.nom
, f.datef
, sc.fk_soc
, sc.fk_user
, u.rowid
, u.firstname
, u.lastname
FROM societe s
JOIN societe_commerciaux sc
ON s.rowid = sc.fk_soc
JOIN user u
ON sc.fk_user = u.rowid
LEFT
JOIN facture f
ON s.rowid = f.fk_soc
GROUP
BY s.rowid
HAVING MAX(f.datef) <= CURRENT_TIMESTAMP - INTERVAL '.$db->escape($dlo).' DAY
';
$resql = $db->query($sql);
if (!$resql) {
dol_print_error($db);
}
背景:
user - 包含用户的名字和姓氏以及主要标识符的表。 rowid
Societe - 带有客户名称s.nom
主要标识的表。 rowid
facture - 带有日期datef
和fk_soc
的客户发票表,它是客户 ID (s.rowid)
societe_commerciaux - 通过将fk_soc
(实际上是 s.rowid)与 fk_user(即 u.rowid)匹配来建立代表每个客户的用户的连接
工作脚本列出了在使用$dlo
和销售代表姓名设置的期间内没有发票的所有客户。
我想做的是,调整结果以向客户显示没有特定销售代表(即用户)的发票。
我有一个工作脚本,它填充了 Dropdown select
<form>
<select name='repselect' onchange='showUser(this.value)'>
<option value="here comes the value for id of sales representative 1">Sales Representative name 1</option>
<option value="here comes the value for id of sales representative 2">Sales Representative name 2</option>
</select>
</form>
Value 字段中的 ID 是来自表 users 的 bot rowid
和来自表fk_ser
的 fk_ser。
我还有一个有效的 ajax 脚本来填充结果。
脚本的工作就像我把print $sql;
在其中,我可以看到我 select 用户之后的查询。
我苦苦挣扎的是如何调整上述查询以仅显示从下拉列表中选择的销售代表的结果。 我将此 ID 传递给文件“script.php”,其中我有$userid = intval($_GET['q']);
其次是查询。 我可以处理 output。这只是我无法正确调整的查询。
此查询从最后一张发票(实际)日期小于(CURRENT_TIMESTAMP - INTERVAL)或从未有发票的客户返回用户代表信息:
$sql = '
SELECT
u.rowid,
u.firstname,
u.lastname
FROM societe s
INNER JOIN societe_commerciaux sc ON s.rowid = sc.fk_soc
INNER JOIN user u ON sc.fk_user = u.rowid
WHERE s.rowid NOT IN (
SELECT f.fk_soc
FROM facture f
GROUP BY f.fk_soc
HAVING MAX(f.datef) > CURRENT_TIMESTAMP - INTERVAL ' . $db->escape($dlo) . ' DAY)
GROUP BY u.rowid, u.firstname, u.lastname
';
您应该使用准备好的语句并且不要在普通查询中粘贴参数 $dlo,以防止 sql 注入。
这是我正在使用的最终查询:
SELECT ';
s.rowid,
s.nom,
s.phone,
s.email,
sc.fk_soc,
sc.fk_user,
u.rowid,
u.firstname,
u.lastname,
f.max_datef
FROM
' . MAIN_DB_PREFIX . 'societe s
INNER JOIN
' . MAIN_DB_PREFIX . 'societe_commerciaux sc ON s.rowid = sc.fk_soc
AND sc.fk_user="' . $this->userId . '"
INNER JOIN
' . MAIN_DB_PREFIX . 'user u ON sc.fk_user = u.rowid
INNER JOIN (
SELECT Max($this->typeDate) As max_datef, fk_soc
FROM
' . MAIN_DB_PREFIX . 'facture
GROUP BY fk_soc
'HAVING max_datef <= CURRENT_TIMESTAMP - INTERVAL $this->interval DAY
) f ON s.rowid = f.fk_soc
ORDER BY max_datef ASC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.