SQL Concat和Join 3 Tables仅返回记录匹配条件

时间:2014-01-07 00:15:10

标签: mysql sql sql-server

我有3张表格,其结构如下所示。

user [user_id | firstname | lastname ]
user_messages [user_message_id | from_user_id | etc ]
user_messages_user_status [user_message_id | user_id | etc ]

我要做的是返回结果,如:

results [user_id | user_message_id | from_user_full_name | to_user_full_name]

这是我到目前为止所做的,但我在“CONCAT_WS:

附近发生错误
SELECT *,
   CONCAT_WS(' ', fu.firstname, fu.lastname) fun
   CONCAT_WS(' ', tu.firstname, tu.lastname) tun
FROM user_messages um
   LEFT JOIN user_messages_user_status umus
     ON um.user_message_id = umus.user_message_id
   INNER JOIN user fu
     ON um.from_user_id = fu.user_id
   INNER JOIN user tu
     ON umus.user_id = tu.user_id
WHERE um.user_id = 'number' OR fun LIKE 'Name%' OR tun LIKE 'Name%'

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您在选择列表中缺少逗号,在fun别名和CONCAT_WS下一列的调用之间缺少逗号:

SELECT *,
   CONCAT_WS(' ', fu.firstname, fu.lastname) fun,
--                                             ^^^
   CONCAT_WS(' ', tu.firstname, tu.lastname) tun
FROM user_messages um
   LEFT JOIN user_messages_user_status umus
     ON um.user_message_id = umus.user_message_id
   INNER JOIN user fu
     ON um.from_user_id = fu.user_id
   INNER JOIN user tu
     ON umus.user_id = tu.user_id
WHERE um.user_id = 'number' OR fun LIKE 'Name%' OR tun LIKE 'Name%'

但是,只需指定其别名,您就无法对派生列WHEREfun使用tun查询。您可以再次指定CONCAT_WS功能 - WHERE CONCAT_WS(' ', fu.firstname, fu.lastname) LIKE 'Name%' - 或者采用不同的搜索方式 - WHERE fu.firstname LIKE 'FName%' AND fu.lastname LIKE 'LName%'。请注意,通过使用此处的函数,数据库引擎很可能无法利用索引。

我相信您可以处理指定所需的列而不是*