我的问题在于第一个子查询选择。我被告知我要返回多行。
$sql = "SELECT
messages.message_id
, messages.sent_timestamp
, messages.content
, messages.subject
, users.user_name
, (SELECT thread_participants.user_id
FROM thread_participants
WHERE thread_participants.user_id !=".$user_id.") as thread_participants
, (SELECT message_read_state.readDate
FROM message_read_state
WHERE message_read_state.message_id = messages.message_id
and message_read_state.user_id =". $user_id.") as ReadState
FROM (messages INNER JOIN users ON messages.sender_user_id = users.user_id
INNER JOIN thread_participants tp ON tp.thread_id = messages.thread_id)
WHERE (((messages.thread_id)=".$thread_id."))
ORDER BY messages.sent_timestamp DESC";
答案 0 :(得分:2)
您可以使用GROUP_CONCAT()
功能在单个字段中获取所有 userIds
试试这个:
$SQL = "SELECT
messages.message_id
, messages.sent_timestamp
, messages.content
, messages.subject
, users.user_name
, (SELECT GROUP_CONCAT(thread_participants.user_id)
FROM thread_participants
WHERE thread_participants.user_id !=".$user_id.") as thread_participants
, (SELECT message_read_state.readDate
FROM message_read_state
WHERE message_read_state.message_id = messages.message_id
and message_read_state.user_id =". $user_id.") as ReadState
FROM (messages INNER JOIN users ON messages.sender_user_id = users.user_id
INNER JOIN thread_participants tp ON tp.thread_id = messages.thread_id)
WHERE (((messages.thread_id)=".$thread_id."))
ORDER BY messages.sent_timestamp DESC";
答案 1 :(得分:0)
在大多数情况下,在mysql中,子查询不如使用单独的查询更佳。在这种情况下,最好使用先前查询中的数据(如id的集合)并在另一个查询中使用它。对您的数据进行一些测试。通常数据量会产生差异;)
同样,分割查询可以帮助您更好地缓存数据。
答案 2 :(得分:0)
我发现这样做的一种方式:
$sql = "SELECT
messages.message_id
, messages.sent_timestamp
, messages.content
, messages.subject
, users.user_name
, tp.user_id as thread_participants
, (SELECT users.user_name FROM users WHERE users.user_id = thread_participants && users.user_id != messages.sender_user_id) as member_names
, (SELECT message_read_state.readDate
FROM message_read_state
WHERE message_read_state.message_id = messages.message_id
and message_read_state.user_id =". $user_id.") as ReadState
FROM (messages INNER JOIN users ON messages.sender_user_id = users.user_id
INNER JOIN thread_participants tp ON tp.thread_id = messages.thread_id)
WHERE (((messages.thread_id)=".$thread_id."))
ORDER BY messages.sent_timestamp DESC";