我有一个特殊情况,其中一条记录的PromotionID(这将是主记录)成为其他一些记录的PID。我需要创建一个MySql语句来获取PromotionMaintenanceID(主记录),PromotionID(主记录),PromotionName(主记录)和所有记录的PromotionID,其中PID =主记录的PromotionID
PromotionMaintenanceID ,PID , PromotionID ,PromotionName
1 | T1 | 12 | Promo1
2 | 12 | 22 | PromoSub
3 | 12 | 33 | PromoSub2
我需要我的结果
PromotionMaintenanceID | PID | PromotionID | PromotionName | Sub PromoID
1 | T1 | 12 | Promo1 |22,33
任何人都知道查询应该如何?
答案 0 :(得分:3)
此查询(SQLFiddle)应该执行您想要的操作:
SELECT p1.PromotionMaintenanceID, p1.PID, p1.PromotionID, p1.PromotionName, GROUP_CONCAT(p2.PromotionID) AS `Sub PromoID`
FROM promotions p1
JOIN promotions p2
ON p2.PID = p1.PromotionID
GROUP BY p1.PromotionID
输出:
PromotionMaintenanceID PID PromotionID PromotionName Sub PromoID
1 T1 12 Promo1 33,22
答案 1 :(得分:0)
为此,您应该能够进行直接加入(或根据您喜欢的方式进行双重选择)
SELECT
a.PromotionID,
a.MaintenanceId,
a.PromotionName,
GROUP_CONCAT(b.PID) as SubIds
FROM
PromotionTable a
LEFT JOIN
PromotionTable b
ON
a.PromotionID = b.PID
//ADD AND's here with a.(column) = b.PID if you absolutely need all the ID's for each column to link up
GROUP BY
a.PromotionID, a.MaintenanceID, a.PromotionName