3

我一直在寻找这个答案。我有两个相同的表,contacts 和 contacts_copy。每个都有全名、公司、街道、城市、州和邮编。如果contacts.street 不为NULL,那么我选择这些项目。如果是,我从重复表中选择这些项目。

SELECT contacts.fullname,
CASE WHEN contacts.street IS NULL
THEN
contacts_copy.Company,
contacts_copy.street,
contacts_copy.city,
contacts_copy.state,
contacts_copy.zip
ELSE
contacts.Company,
contacts.street,
contacts.city,
contacts.state,
contacts.zip
END CASE
FROM contacts_copy, contacts
WHERE contacts.Company = contacts_copy.fullname
AND contacts.kind = 'Person'
ORDER BY contacts.last DESC



I keep getting:
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
contacts_copy.street,
contacts_copy.city,
contacts_copy.state,
contacts_cop' at line 4

必须有一种更简单的方法来做到这一点。MySQL 错误消息非常无用。

谢谢,

4

3 回答 3

3

我认为你不能用 MySQL 或我见过的任何类型的 SQL 来做到这一点。您选择的列必须是特定的,但值可以是有条件的。

您可以做的是IF()为结果中的每一列设置一个子句:

SELECT contacts.fullname,
  IF(contacts.street IS NULL, contacts_copy.Company, contacts.Company),
  ...

那应该有同样的效果。

于 2012-08-28T23:12:00.367 回答
1

编辑:表别名已更改,并company.kind添加了额外的子句。

一种方法是使用UNION

SELECT person.last,
       person.fullname,
       person.Company,
       person.street,
       person.city,
       person.state,
       person.zip
  FROM contacts person
  WHERE person.kind = 'Person'
    AND person.street IS NOT NULL
UNION
SELECT person.last,
       person.fullname,
       company.Company,
       company.street,
       company.city,
       company.state,
       company.zip
  FROM contacts person
  INNER JOIN contacts company ON person.Company = company.fullname
  WHERE company.kind = 'Company'
    AND person.kind = 'Person'
    AND person.street IS NULL
ORDER BY 1 DESC

不幸的是,这确实需要您在结果中包含排序列。

鹰眼注意:与最初的尝试不同,此版本将包括行 from personwhere streetis notNULL尽管不company存在匹配的条目。

于 2012-08-28T23:27:58.470 回答
0
SELECT c1.fullname AS fullname,  
c1.Company AS company,  
c1.first AS firstname,  
c1.last AS lastname,  
c2.street AS street,  
c2.city AS city,  
c2.state AS state,  
c2.zip AS zip   
FROM contacts AS c1, contacts AS c2 
WHERE c1.kind = 'Person'   
AND c1.Company = c2.fullname   
ORDER BY c1.last ASC;  

是答案。

于 2012-09-04T22:16:57.230 回答