我有一个查询,首先从表格案例中选择一行,之后我从连接表付款中选择了5行。选择的结果显示5个结果。我想限制它只显示第一个选择的一个结果,但仍然选择了内存中连接表的所有5个结果。
到目前为止,我的查询如下:
SELECT c.*,
DATE_FORMAT( ADDDATE(c.proposal_date, INTERVAL 30 DAY),'%Y-%m-%d') AS expiration_date_30,
(SELECT name FROM members rp WHERE rp.id = c.resonsible_partner) as responsible_partner,
FROM cases c
LEFT JOIN payments AS inv ON inv.caseid = c.id
WHERE c.id = $id
欢迎任何帮助!
此案例中的示例输出应显示:
来自表格案例的应在屏幕上显示c.*
:id, casename, proposal_date
这应该控制必须显示多少行。
id | casename | proposal_date |
------------------------------
300 | One | 2016-05-05 |
来自桌面付款的应显示:payment_percentage_01 = 25, payment_percentage_02 = 30, payment_number_01 = 1, payment_number_02 = 2
id | caseid | payment_percentage | payment number |
---------------------------------------------------
1 | 300 | 25 | 1 |
2 | 300 | 30 | 2 |
答案 0 :(得分:1)
这似乎是一个表格枢轴问题,不确定你是否真的想要这个,但只是尝试一下,也许是工作:
SELECT
c.*,
DATE_FORMAT( ADDDATE(c.proposal_date, INTERVAL 30 DAY),'%Y-%m-%d') AS expiration_date_30,
-- (SELECT name FROM members rp WHERE rp.id = c.resonsible_partner) as responsible_partner,
MAX(CASE WHEN p.id = 1 THEN p.payment_percentage END) AS payment_percentage_01,
MAX(CASE WHEN p.id = 2 THEN p.payment_percentage END) AS payment_percentage_02,
MAX(CASE WHEN p.id = 1 THEN p.`payment number` END) AS payment_number_01,
MAX(CASE WHEN p.id = 2 THEN p.`payment number` END) AS payment_number_02
FROM cases c
LEFT JOIN payments p
ON c.id = p.caseid
GROUP BY c.id
<强> 编辑: 强>
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(CASE WHEN p.id = ''',
id,
''' THEN p.payment_percentage END) AS payment_percentage',
id
), ',',
CONCAT(
'MAX(CASE WHEN p.id = ''',
id,
''' THEN p.`payment number` END) AS payment_number',
id
)
) INTO @sql
FROM payments;
SET @sql = CONCAT('
SELECT c.*,
DATE_FORMAT( ADDDATE(c.proposal_date, INTERVAL 30 DAY),''%Y-%m-%d'') AS expiration_date_30, '
, @sql
, ' FROM cases c
LEFT JOIN payments p
ON c.id = p.caseid
GROUP BY c.id;');
-- SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;