我正在尝试结合一些查询,但似乎无法确定。我想知道是否有人可以指出我正确的方向。
以下是声明:
SELECT
I.id,
I.custname,
I.custemail,
I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts
FROM images I
WHERE I.stat = 0
SELECT
COUNT(*) AS total1
FROM images
WHERE stat = 1 AND sku = ?
SELECT
COUNT(*) AS total2
FROM images
WHERE stat = 1
AND sku IN (SELECT subsku FROM combo WHERE sku = ?)
现在我正在使用 3 个单独的查询,并使用代码来添加两个总数并显示它们。但是我现在需要能够按总数的总和进行排序,所以我想将所有这些数据放入一个语句中......就像:
SELECT
I.id,
I.custname,
I.custemail,
I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts,
SUM(total1+total2)
FROM images I
WHERE I.stat = 0
但我不确定该怎么做。我尝试了下面的代码,但失败了:
SELECT
I.id,
I.custname,
I.custemail,
I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts),'%l:%i:%s %p, %c/%e/%Y') AS ts,
(
SELECT COUNT(*) AS total1 FROM images WHERE stat = 1 AND (
sku IN (
SELECT subsku FROM combo WHERE sku = I.sku
) OR sku = I.sku)
) AS skuct
FROM images I
WHERE stat = 0
任何帮助将不胜感激。非常感谢!
更新
首先感谢所有提供帮助的人。我一直在处理查询并认为我越来越近了,但我现在遇到了“子查询返回超过 1 行”错误:
SELECT
I.id,
I.custname,
I.custemail,
I.sku,
DATE_FORMAT(FROM_UNIXTIME(I.ts), '%l:%i:%s %p, %c/%e/%Y') AS ts,
(
SELECT COUNT(*)
FROM images
WHERE stat = 1
AND sku = I.sku
OR sku IN(
SELECT subsku FROM combo WHERE sku = I.sku
)
GROUP BY sku
) AS total
FROM images I
WHERE stat = 0
问题是子查询SELECT subsku FROM combo WHERE...
返回结果集(0+ 行)与标量。如果我能弄清楚那部分,我认为这会奏效。