我有这个问题:
SELECT
s.id AS id,
s.item_id,
i.type_id AS type_id,
i.description AS description,
i.owner_id,
s.buyer_id,
i.receivedate,
i.statusdate,
i.baseprice,
i.salepercentage,
i.status_id,
s.posteddate,
s.closingdate,
s.discountdate,
s.discountrate,
t.description AS type_description,
st.description AS status_description
FROM
sale s
LEFT JOIN item i ON s.item_id=i.id
LEFT JOIN TYPE t ON i.type_id=t.id
LEFT JOIN STATUS st ON i.status_id=st.id
WHERE s.flag_id != 2
GROUP BY s.id
ORDER BY s.closingdate;
它工作正常,但作为最后一步,我需要从另一个名为customer
的表中提取连接的firstname和lastname字段,以便同时 i.owner_id
和{ {1}}字段。
我已经接近使用以下内容:
s.buyer_id
当我使用customer表中的条目测试它时,如下所示:
SELECT
s.id AS id,
s.item_id,
i.type_id AS type_id,
i.description AS description,
i.owner_id,
s.buyer_id,
i.receivedate,
i.statusdate,
i.baseprice,
i.salepercentage,
i.status_id,
s.posteddate,
s.closingdate,
s.discountdate,
s.discountrate,
t.description AS type_description,
st.description AS status_description,
GROUP_CONCAT(CONCAT(c.firstname, ' ', c.lastname) ORDER BY i.owner_id, s.buyer_id)
FROM
sale s
LEFT JOIN item i ON s.item_id=i.id
LEFT JOIN TYPE t ON i.type_id=t.id
LEFT JOIN STATUS st ON i.status_id=st.id
LEFT JOIN CUSTOMER c ON i.owner_id=c.id OR s.buyer_id=c.id
WHERE s.flag_id != 2
GROUP BY s.id
ORDER BY s.closingdate;
销售表中的商品有:
id=3, firstname="John", lastname="Doe"
id=10, firstname="Jane", lastname="Do"
owner_id=3, buyer_id=10
owner_id=10, buyer_id=3
列返回
GROUP_CONCAT()
我无法知道哪个是所有者,哪个是买家完全脱离逗号分隔的位置,因为我希望的结果是
Jane Do,John Doe
Jane Do,John Doe
用于销售商品。
是否可以确保返回的结果集将以受控顺序返回John Doe,Jane Do
Jane Do,John Doe
列表(即第一个客户将与GROUP_CONCAT()
和第二个客户owner_id
相关联1}})?
答案 0 :(得分:3)
我建议加入客户表两次。一次为买家,一次为所有者:
SELECT ...
GROUP_CONCAT(CONCAT(buyer.firstname, ' ', buyer.lastname) AS buyers,
GROUP_CONCAT(CONCAT(owner.firstname, ' ', owner.lastname) AS owners
...
LEFT JOIN customer AS buyer ON s.buyer_id=buyer.id
LEFT JOIN customer AS owner ON i.owner_id=owner.id
如果您需要将数据分开,请将其分开。
答案 1 :(得分:1)
问题是你是混合所有者和买主
只需单独加入;
只要为每个实例使用不同的别名,加入同一个表就没问题了。
SELECT
s.id AS id, s.item_id
, i.type_id AS type_id, i.description AS description, i.owner_id
, s.buyer_id
, i.receivedate, i.statusdate, i.baseprice, i.salepercentage, i.status_id
, s.posteddate, s.closingdate, s.discountdate, s.discountrate
, t.description AS type_description
, st.description AS status_description
, GROUP_CONCAT(
CONCAT(co.firstname, ' ', co.lastname,',',cb.firstname,' ',cb.lastname)
ORDER BY co.id,cb.id) as first_owner_than_buyer
FROM sale s
LEFT JOIN item i ON s.item_id=i.id
LEFT JOIN TYPE t ON i.type_id=t.id
LEFT JOIN STATUS st ON i.status_id=st.id
LEFT JOIN CUSTOMER co ON (i.owner_id=co.id)
LEFT JOIN CUSTOMER cb ON (s.buyer_id=cb.id)
WHERE s.flag_id != 2
GROUP BY s.id
ORDER BY s.closingdate;