我需要获取用户名和用户名以显示消息。
我有两张桌子 一个用户表
CREATE TABLE IF NOT EXISTS USERS(
USER_ID INT UNSIGNED NOT NULL,
USER_EMAILID VARCHAR(100) CHARACTER SET 'latin1' COLLATE 'latin1_bin' NOT NULL,
USER_FIRST_NAME VARCHAR(100) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
USER_LAST_NAME VARCHAR(100) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
PRIMARY KEY (USER_ID),
INDEX idx_USER_CONFIG_id2 (USER_EMAILID ASC)
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;
和电子邮件表
CREATE TABLE IF NOT EXISTS EMAIL (
MAIL_ID TINYINT UNSIGNED NOT NULL,
FROM_ADD INT UNSIGNED NOT NULL,
TO_ADD INT UNSIGNED DEFAULT NULL,
EMAIL_SUBJECT VARCHAR(75) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' DEFAULT NULL,
MESSAGE TEXT CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' DEFAULT NULL,
PRIMARY KEY (MAIL_NO)
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;
我需要查询特定用户的电子邮件,以下是我所拥有的 在这样做时我也需要带上他们的名字。我怎样才能做到这一点?
编辑:( OP在评论中提供的查询)
SELECT B.TO_ADD, B.FROM_ADD, A.USER_FIRST_NAME, B.MESSAGE
FROM EMAIL B LEFT JOIN
USERS A
ON (A.USER_ID = B.FROM_ADD OR A.USER_ID = B.TO_ADD)
ORDER BY A.USER_FIRST_NAME DESC;
答案 0 :(得分:1)
我想你只想要两个left join
s:
SELECT e.TO_ADD, e.FROM_ADD, ufrom.USER_FIRST_NAME, uto.USER_FIRST_NAME, e.MESSAGE
FROM EMAIL e LEFT JOIN
USERS ufrom
ON ufrom.USER_ID = e.FROM_ADD LEFT JOIN
USERS uto
ON uto.USER_ID = e.TO_ADD
ORDER BY ufrom.USER_FIRST_NAME DESC;