mySQL UNION 错误
我在涉及联合的 sql 连接方面遇到问题。我试图从 2 个表中提取 COUNT 和一个字段,但出现错误。
查询:
$sql_result7 = mysql_query("(SELECT COUNT (*) as alertcount, date as alertdate FROM alerts WHERE to_id='$id' AND date > '$lastcheck') UNION (SELECT COUNT (*) as mailcount, date maildate FROM mobmail WHERE to_id='$id' AND to_del=0 AND seen = '0')", $db);
$rs7 = mysql_fetch_array($sql_result7);
$alerts = $rs7[alertcount];
$mails = $rs7[mailcount];
$last_alert = $rs7[alertdate];
$last_mail = $rs7[maildate];
这与 date as alertdate
部分有关吗?
我得到的错误是:
警告:mysql_fetch_array():提供的参数不是有效的 MySQL 结果资源
Im having trouble with a sql join involving a union. I'm trying to pull a COUNT and a field from 2 tables but getting an error.
The query:
$sql_result7 = mysql_query("(SELECT COUNT (*) as alertcount, date as alertdate FROM alerts WHERE to_id='$id' AND date > '$lastcheck') UNION (SELECT COUNT (*) as mailcount, date maildate FROM mobmail WHERE to_id='$id' AND to_del=0 AND seen = '0')", $db);
$rs7 = mysql_fetch_array($sql_result7);
$alerts = $rs7[alertcount];
$mails = $rs7[mailcount];
$last_alert = $rs7[alertdate];
$last_mail = $rs7[maildate];
Is it something to do with the date as alertdate
part?
The error im getting is:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了
COUNT
和(*)
之间的空格之外,还有另一个问题。您不能在 PHP 代码中使用$rs7[mailcount]
或$rs7[maildate]
,因为您的查询相当于:并且将返回两行且仅 2 列:
解决此问题的两种方法:
要么保留查询(将
UNION
更改为UNION ALL
以确保始终获得 2 行),然后更改 PHP 以使用 2 行行。或者将查询更改为:
Besides the space between
COUNT
and(*)
, there is another issue. You can't use$rs7[mailcount]
nor$rs7[maildate]
in your PHP code because your query is equivalent to:and will return two rows and only 2 columns:
Two ways to solve this problem:
Either keep the query (changing the
UNION
toUNION ALL
to ensure that you always get 2 rows) and chnage the PHP to use the 2 rows.Or change the query to: