大家都知道stackoverflow!
我正在创建一个SQL字符串,我得到每个计划的最新订单(只有一个)。
我的SQL字符串现在看起来像这样:
$sql = "SELECT
o.order_id,
p.plan_id,
u.user_id,
m.module_id,
c.title AS category_title,
m.title
FROM
(SELECT
user_id,
status,
order_id,
payment_method_id,
time_created
FROM
orders
ORDER BY
order_id DESC) AS o
JOIN
plans AS p
ON
p.user_id = o.user_id
JOIN
modules AS m
ON
p.module_id = m.module_id
JOIN
categories AS c
ON
m.category_id = c.category_id
JOIN
users AS u
ON
p.user_id = u.user_id
WHERE
p.status = :status
AND
p.payment = 0
AND
o.status = :status
AND
p.subscription_id != ''
GROUP BY
p.plan_id";
// Here i get the status variable
$stmt->bindParam(':status', $status, PDO::PARAM_INT);
我想做的是:
$sql = "SELECT
o.order_id,
p.plan_id,
u.user_id,
m.module_id,
c.title AS category_title,
m.title
FROM
(SELECT
user_id,
status,
order_id,
payment_method_id,
time_created
FROM
orders
WHERE
module_id = p.module_id
AND
user_id = p.user_id
LIMIT 1
ORDER BY
order_id DESC) AS o
JOIN
plans AS p
ON
p.user_id = o.user_id
JOIN
modules AS m
ON
p.module_id = m.module_id
JOIN
categories AS c
ON
m.category_id = c.category_id
JOIN
users AS u
ON
p.user_id = u.user_id
WHERE
p.status = :status
AND
p.payment = 0
AND
o.status = :status
AND
p.subscription_id != ''
GROUP BY
p.plan_id";
我在访问子查询中的p.module_id
和p.user_id
变量时遇到了很大麻烦。
我的问题是:如何在子查询中访问p.module_id
和p.user_id
?或者有更好的方法吗?
答案 0 :(得分:1)
你不能这样做......试试这个:
$sql = "SELECT o.order_id, p.plan_id, u.user_id, m.module_id, c.title AS category_title, m.title
FROM
(SELECT user_id, status, order_id, module_id, payment_method_id, time_created
FROM orders ORDER BY order_id DESC) AS o
JOIN
plans AS p ON p.user_id = o.user_id
JOIN
modules AS m ON p.module_id = m.module_id AND m.module_id=o.module_id
JOIN
categories AS c ON m.category_id = c.category_id
JOIN
users AS u ON p.user_id = u.user_id
WHERE
p.status = :status AND p.payment = 0 AND o.status = :status AND p.subscription_id != ''
AND p.user_id is not null AND m.module_id is not null
GROUP BY p.plan_id";
在查询的最后一次尝试使用LIMIT 1 ....
在这里,您希望从订单表中获取记录,其中包含plans的user_id和modules_id的模块,您可以在连接条件中添加这些记录,并确保在主查询的WHERE子句中不是null。因为user_id条件已经存在,所以我只在模块表的连接条件中添加了module_id,在条件中添加了两个。