如何在单行中从同一个表中连接多个行

时间:2013-06-26 06:00:51

标签: php mysql

我有这个查询。另请参阅表格架构

的以下内容

http://sqlfiddle.com/#!2/36d20/14

SELECT
  ca1.*,
  ca2.*
FROM Contact_Address AS ca1
  JOIN Contact_Address AS ca2
    ON ca1.ca_contact_id = ca2.ca_contact_id
WHERE ca1.ca_contact_id = 1
    AND ca1.ca_type = 'PRI'
    AND ca2.ca_type = 'SEC'

我必须将包含在同一个表中的两行组合成单行。它们包含类型'PRI','SEC'。但条件是对于一个用户它将包含两个行而另一个用户只包含它们之一。

请帮忙, 感谢

1 个答案:

答案 0 :(得分:0)

SELECT
  ca1.ca_contact_id as ci1,ca1.ca_type as type1,
  ca2.ca_contact_id as ci2, ca2.ca_type as type2
FROM Contact_Address AS ca1
  JOIN Contact_Address AS ca2
    ON ca1.ca_contact_id = ca2.ca_contact_id
WHERE ca1.ca_contact_id = 1
    AND ca1.ca_type = 'PRI'
    AND ca2.ca_type = 'SEC'

SqlFiddle

您必须指定您的列名