且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在一个结果行中选择多行

更新时间:2023-12-04 13:01:46

您可以使用GROUP_CONCAT()GROUP BY获得所需的结果:

You can use GROUP_CONCAT() and GROUP BY to get the results you desire:

SELECT t1.*, GROUP_CONCAT(t2.date) AS dates
FROM Table1 t1
LEFT JOIN Table2 t2
  ON t2.ID_adv = t1.ID_adv
GROUP BY t1.ID_adv

这将返回每个广告的所有日期,并以逗号分隔.在Table2中没有特定广告的日期的地方,dates列的值为NULL.

This returns all the dates for each advertisement, concatenated by commas. Where there are no dates in Table2 for a particular advertisment, you'll get NULL for the dates column.

要定位特定广告,只需添加WHERE子句:

To target a particular advertisement, simply add the WHERE clause:

SELECT t1.*, GROUP_CONCAT(t2.date) AS dates
FROM Table1 t1
LEFT JOIN Table2 t2
  ON t2.ID_adv = t1.ID_adv
WHERE t1.ID_adv = 3
GROUP BY t1.ID_adv