MySQL多个联接具有不同的顺序依据和限制

时间:2016-09-05 21:26:35

标签: mysql join limit

我一直在寻找这个,要么它是我的梦想,也不存在,或者我没有使用正确的搜索词。我所知道的关于SQL的一切都是自学成才,而我用它做的事情通常都非常简单,所以对你来说可能是直观和简单的并不一定是我。

我想知道你是否可以在MySQL中使用多个连接语句,结果不同,如:

SELECT client.firstname, client.lastname, service.date,
payment.date, payment.amount
FROM client
JOIN service ON client.id = service.clientid
ORDER BY service.date DESC
LIMIT 8 
JOIN payment ON client.id = payment.clientid
ORDER BY payment.date DESC
LIMIT 2;

我正在尝试获取输出显示客户的最后几个月付款以及最近几个月的每周服务,以便一目了然地显示使用该服务的客户是否按月付款。

提前感谢您提供给我的任何见解。

1 个答案:

答案 0 :(得分:1)

看起来你加入时非常时髦,或者你正试图使用​​工会。

限制(固定)

SELECT client.firstname, client.lastname, service.date,
payment.date, payment.amount
FROM client
JOIN service ON client.id = service.clientid
JOIN payment ON client.id = payment.clientid
ORDER BY service.date DESC, payment.date DESC
LIMIT 8;

联盟

SELECT client.firstname, client.lastname, service.date,
payment.date, payment.amount
FROM client
JOIN service ON client.id = service.clientid
JOIN payment ON client.id = payment.clientid
ORDER BY service.date DESC
LIMIT 8
UNION ALL
SELECT client.firstname, client.lastname, service.date,
payment.date, payment.amount
FROM client
JOIN service ON client.id = service.clientid
JOIN payment ON client.id = payment.clientid
ORDER BY payment.date DESC
LIMIT 2;