我需要解决基于字段连接表的问题。 我有3张桌子:
NEWS (id,title)
COMMENTS (id,idtopic,message)
NOTIFICATIONS (iduser,idnews,idtopic,idpost)
当COMMENTS
有idtopic=0
时,它是一个主题,当它> 0时,它就是主题的回复。
通过NOTIFICATIONS
用户了解各种信息。
现在我想从其他表中获取字段,选择NOTIFICATIONS
。
基地SELECT
是:
SELECT idnews,idtopic,idpost FROM notifications WHERE iduser=X
现在我想加入:
我想我应该做这样的事情:
SELECT CASE idnews>0 THEN ??,
CASE idtopic>0 THEN ??, CASE idpost>0 THEN
FROM NOTIFICATIONS
我想总是返回一个带有标题或消息的字段,因为其中一个idnews / idtopic / idpost总是> 0
如何在不加入每条记录的每个表的情况下选择SELECT内部?我不想做
SELECT *
FROM NOTIFICATIONS
LEFT JOIN NEWS ON NOTIFICATIONS.idnews=NEWS.id
LEFT JOIN COMMENTS ON NOTIFICATIONS.idtopic=COMMENTS.id
LEFT JOIN COMMENTS ON NOTIFICATIONS.idpost=COMMENTS.id
因为表现会比CASE WHEN idnews>0 OR idtopic>0 OR idpost>0
更差。
答案 0 :(得分:0)
我不知道这是否是你的要求,但是,你可以选择这样的选择......
SELECT donor.idno, name, contamt, driveno
FROM donor, donation
WHERE donor.idno = donation.idno AND driveno > any
(SELECT driveno FROM drive WHERE drivename = 'Animal Home');
答案 1 :(得分:0)
我希望我能正确理解你,试试这个:
create procedure printNotification(in input_userid int)
BEGIN
DECLARE id_news int;
DECLARE id_topic int;
DECLARE id_post int;
DECLARE id_title char(30);
DECLARE id_message char(30);
SELECT idnews,idtopic,idpost INTO @id_news,@id_topic,@id_post FROM NOTIFICATIONS WHERE iduser=input_userid;
IF(id_news>0) THEN
SELECT title INTO @id_title FROM NEWS WHERE id=id_news;
END IF;
IF(id_topic>0) THEN
SELECT message INTO @id_message FROM COMMENTS WHERE id=idtopic;
END IF;
IF(idpost>0) THEN
SELECT message INTO @id_message FROM COMMENTS WHERE id=idpost;
END IF;
END//