如何用LEFT JOIN修复这个sql?

时间:2012-01-17 12:12:44

标签: mysql sql

我有以下两个mysql表:

mysql> desc subscriptions;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(6)       | NO   | PRI | NULL    | auto_increment |
| id_user    | int(6)       | NO   | MUL | NULL    |                |
| id_package | int(4)       | NO   |     | NULL    |                |
| expiry     | date         | YES  |     | NULL    |                |
| ip         | varchar(100) | NO   |     | NULL    |                |
| amount     | double       | NO   |     | NULL    |                |
| processed  | tinyint(4)   | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)


mysql> desc packages;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(6)       | NO   | PRI | NULL    | auto_increment |
| id_panel | tinyint(4)   | NO   |     | NULL    |                |
| name     | varchar(100) | NO   |     | NULL    |                |
| price    | double       | NO   |     | NULL    |                |
| period   | varchar(50)  | NO   |     | NULL    |                |
| days     | int(11)      | NO   |     | NULL    |                |
| visible  | tinyint(4)   | NO   |     | NULL    |                |
| payment  | tinyint(4)   | NO   |     | 1       |                |
+----------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

我使用以下查询来检索所有包和相关的USER到期日期(特定包的日期)。

SELECT packages.id, packages.name, packages.price, packages.period, packages.days, MAX(subscriptions.expiry) as expiry
FROM packages LEFT JOIN subscriptions
ON subscriptions.id_package = packages.id AND subscriptions.processed = 1 AND subscriptions.id_user = 1
WHERE packages.visible = 1
GROUP BY subscriptions.id_user
ORDER BY packages.id_panel

我的问题是,如果没有订阅特定包,则查询不会显示包。

我必须显示所有页面....如果用户有订阅,请检查MAX到期日期(因为我跟踪用户所做的所有子项)。

如何显示所有包和相关用户的到期日期? (如果没有订阅包显示NULL)

2 个答案:

答案 0 :(得分:1)

您按subscriptions.id_user进行分组,但是您从packages表格中选择了所有非分段广告。您确定要按正确的字段进行分组吗?

看起来应该是packages.id ...

答案 1 :(得分:0)

简单...只需将packages.visible = 1条件移动到ON子句中即可!

SELECT packages.id, packages.name, packages.price, packages.period, packages.days, MAX(subscriptions.expiry) as expiry
FROM packages
LEFT JOIN subscriptions ON subscriptions.id_package = packages.id
    AND subscriptions.processed = 1
    AND subscriptions.id_user = 1
    AND packages.visible = 1
GROUP BY 1,2,3,4,5
ORDER BY packages.id_panel

这种方法是唯一的方式,可以让条件进入LEFT JOIN,这是一个值得记住的好方法。

注意:您的分组列表也不正确